发表文章

[Javascript] 承诺风格 Promise style[javascript-styleguide]

CERios 2017-10-9 22

我们可以测试 git 问题将如何作为讨论风格选择和人们喜欢的地方。

从詹姆斯的松弛通道上开始的讨论中取消了这个。

Lehgo!

functionsomethingAsync() {
    returnnewPromise((resolvereject=> {
        // fetch some stuff from somewhere
    });
}

functionanotherAsync(data) {
    returnnewPromise((resolvereject=> {
        // do something with data passed in
    });
}

// not nice
somethingAsync().then(stuff=> {
    // handle data
    console.log(stuff);
}, (err=> {
    console.log(err);
});

// very not nice
somethingAsync().then(stuff=> {
    anotherAsync(stuff).then(moreStuff=> {
        console.log(moreStuff);
    err=> {
        // error handling for nested promise
        console.log(err);
    });
}, (err=> {
    // error handling for first promise
    console.log(err);
});


// nicer
somethingAsync
    .then((stuff=> {
        console.log(stuff);
    })
    .catch((err=> {
        console.log(err);
    })
    .finally=> {
        // optional clean up
    });

// allows for chaining multiple promises with just 1 error handler.
somethingAsync
    .then(anotherAsync)
    .then((moreStuff=> {
        // result of second promise
        console.log(moreStuff);
    })
    .catch((err=> {
        // catch rejections from both promises in the same block
    });
    
// real life 
halClient
    .$post(`${apiUrl}/api/v1/login/admin_sso/${companyId}`, {}, data)
    .then((login=> {
        constparams= {auth_token:login.auth_token};
        login
            .$get('administrator', params)
            .then((admin=> {
                defer.resolve(admin);
            })
            .catch((err=> {
                defer.reject(err);
            });
    })
    .catch((err=> {
        defer.reject(err);
    });
原文:

Thought we could test how git issues will serve as a place to discuss style options and what people prefer.

Lifted this from a discussion that was started on the slack channel by James.

Lehgo!

function somethingAsync() {
    return new Promise((resolve, reject) => {
        // fetch some stuff from somewhere
    });
}

function anotherAsync(data) {
    return new Promise((resolve, reject) => {
        // do something with data passed in
    });
}

// not nice
somethingAsync().then(stuff => {
    // handle data
    console.log(stuff);
}, (err) => {
    console.log(err);
});

// very not nice
somethingAsync().then(stuff => {
    anotherAsync(stuff).then(moreStuff => {
        console.log(moreStuff);
    }, err => {
        // error handling for nested promise
        console.log(err);
    });
}, (err) => {
    // error handling for first promise
    console.log(err);
});


// nicer
somethingAsync
    .then((stuff) => {
        console.log(stuff);
    })
    .catch((err) => {
        console.log(err);
    })
    .finally(() => {
        // optional clean up
    });

// allows for chaining multiple promises with just 1 error handler.
somethingAsync
    .then(anotherAsync)
    .then((moreStuff) => {
        // result of second promise
        console.log(moreStuff);
    })
    .catch((err) => {
        // catch rejections from both promises in the same block
    });
    
// real life 
halClient
    .$post(`${apiUrl}/api/v1/login/admin_sso/${companyId}`, {}, data)
    .then((login) => {
        const params = {auth_token: login.auth_token};
        login
            .$get('administrator', params)
            .then((admin) => {
                defer.resolve(admin);
            })
            .catch((err) => {
                defer.reject(err);
            });
    })
    .catch((err) => {
        defer.reject(err);
    });
相关推荐
最新评论 (22)
piotrsiatkowski 2017-10-9
1

我非常喜欢这个款式。整洁干净。读.但你为什么要在现实生活的例子中承诺承诺?我们是否还可以检查是否可以打开语法颜色?

原文:

I like this style very much. Neat and clean. Readable. But why do you want to handle promise inside a promise in real life example? Can we also check if we can turn syntax colours on?

jthomas1 2017-10-9
2

我想为现实生活中的例子, 你想这样做:

halClient
    .$post(`${apiUrl}/api/v1/login/admin_sso/${companyId}`, {}, data)
    .then((login=> {
        constparams= { auth_token:login.auth_token };
        returnlogin.$get('administrator', params)
    })
    .then((admin=> {
        defer.resolve(admin);
    })
    .catch((err=> {
        // all errors handled in one place
        defer.reject(err);
    });
原文:

I think for the real life example you want to do this:

halClient
    .$post(`${apiUrl}/api/v1/login/admin_sso/${companyId}`, {}, data)
    .then((login) => {
        const params = { auth_token: login.auth_token };
        return login.$get('administrator', params)
    })
    .then((admin) => {
        defer.resolve(admin);
    })
    .catch((err) => {
        // all errors handled in one place
        defer.reject(err);
    });
CERios 2017-10-9
3

鼎鼎@jthomas1获胜!

@victorjeman将准备好您的 cookie

原文:

ding ding ding @jthomas1 wins!

@victorjeman will get your cookie ready

jthomas1 2017-10-9
4
victorjeman 2017-10-9
5

那么我们如何在整个应用程序中进行这样的更改?你有具体的步骤吗?这是一个人做的事情, 还是每个人在他的方式得到这样的东西时做的事情?

原文:

So how we guys could proceed with changing something like this in the whole application? Do you have some specific steps? Is this something done by a single person, or this is something done by every person when he gets something like this in his way ?

jthomas1 2017-10-9
6

@victorjeman我们的想法是, 我们同意一种风格, 我们想使用前进的所有新的东西, 当你做一些现有的代码, 有旧的语法, 你可以整理它, 当你去的一些工作。

一般情况下, 代码审查过程是为了提高风格点, 如单元测试等, 以捕捉 bug 和意外行为

原文:

@victorjeman The idea is that we agree on a style that we want to use going forward for all new stuff and when you're doing some work in some existing code that has the old syntax you can tidy it up as you go along.

Generally the code review process is for raising stylistic points such as this as the unit tests etc are for catching bugs and unexpected behaviour

jthomas1 2017-10-9
7

当我们谈到在我们的复古的一天, 我不知道有多少怪异的代码是咖啡 > es6 转换的结果。

原文:

As we talked about the other day in our retro I do wonder how much weird looking code is the result of the coffee -> es6 conversion.

CERios 2017-10-9
8

我们都应该遵循童子军的原则。

童子军有一个规则: "总是离开营地清洁比你发现它。如果你在地上发现了一个烂摊子, 你就把它清理干净, 不管谁会把事情弄得一团糟。你有意改善下一组露营者的环境。实际上, 这一规则的最初形式, 由童子军之父史密斯--鲍威尔所写, 是 "试图让这个世界比你发现的更好一点"。

如果我们在代码中遵循一个类似的规则: "总是比您签出时检查干净的模块"。无论最初的作者是谁, 如果我们总是做一些努力, 不管有多小, 改进模块。结果会怎样?

@victorjeman

原文:

We should all follow the boy scout principle.

The Boy Scouts have a rule: "Always leave the campground cleaner than you found it." If you find a mess on the ground, you clean it up regardless of who might have made the mess. You intentionally improve the environment for the next group of campers. Actually the original form of that rule, written by Robert Stephenson Smyth Baden-Powell, the father of scouting, was "Try and leave this world a little better than you found it."

What if we followed a similar rule in our code: "Always check a module in cleaner than when you checked it out." No matter who the original author was, what if we always made some effort, no matter how small, to improve the module. What would be the result?

@victorjeman

CERios 2017-10-9
9

也可能值得提及一些隐含的东西, 我们应该都在同一页上。不具体与承诺, 但。

参数总是有括号。

.then((login) => {
    const params = { auth_token: login.auth_token };
    return login.$get('administrator', params)
})

喜欢 const 超过让

const params = { auth_token: login.auth_token };
return login.$get('administrator', params)

总是多行/避免单行返回

.catch((err) => {
    defer.reject(err);
});

人们是怎么想的?

原文:

Also probably worth mentioning a few things that are implied, that we should all be on the same page for. Not specifically to do with promises but..

Argument always has brackets.

.then((login) => {
    const params = { auth_token: login.auth_token };
    return login.$get('administrator', params)
})

Prefer const over let

const params = { auth_token: login.auth_token };
return login.$get('administrator', params)

Always multiple line / Avoid single line return

.catch((err) => {
    defer.reject(err);
});

What do people think?

jthomas1 2017-10-9
10

我个人的偏好是把括号放在一个参数函数的周围 (通常在任何地方不只是许诺)。

myPromise().then(stuff=> {
    doSome(stuff);
})

优点:

  • 说明书上说你不需要
  • 少打字
  • 看起来更整洁

利弊:
?

原文:

My personal preference is to drop the parens around a single parameter function (generally anywhere not just promises).

myPromise().then(stuff => {
    doSome(stuff);
})

Pros:

  • the specification says you don't need them
  • less typing
  • looks neater

Cons:
?

flaviotulino 2017-10-9
11

我唯一的评论是不要把诺言和 $q 图书馆混为一谈。
说实话, 我们应该把 $q 除掉。

@jthomas1通常我遵循规范, 并且我同意对单个参数括号较少的语法。

原文:

The only remark I have is about not mixing Promise and $q library.
To be honest, we should get rid of $q.

@jthomas1 usually I follow the specification, and I agree with the parens-less syntax for a single param.

jthomas1 2017-10-9
12

叶当我写的原始 jsfiddle 我只是使用的承诺, 因为我一直在节点上使用它, 所以我的手在汽车驾驶员:D

可悲的承诺是不支持在所有的 ie: ' (

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise

原文:

Yeh when I wrote the original jsfiddle I just used Promise cos I've been using it in node all the time so my hands were on auto pilot :D

Sadly Promise is not supported in Internet Explorer at all :'(

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise

flaviotulino 2017-10-9
13

@jthomas1巴贝尔对此代码。我一直在商业上使用的承诺, 我从来没有问题。

原文:

@jthomas1 babel has a polyfill for this. I've always used Promise commercially and I've never had problems.

piotrsiatkowski 2017-10-9
14

$q 仍然是有用的例如对于 $q, 所有功能。对于请求, 我们可能应该使用 $http 或包装在它周围。

我认为一个班轮是很好的选择与 = > 和一些转换。但是, 在承诺的情况下, 我们应该总是准备的链接, 这就是为什么我认为我们应该总是开始一条新的线。

我想我们应该在 () 周围打开一个关于箭头表达式中的参数的单独问题。

我同意童子军的规则。这就是为什么我们要制定一个客观的指标来衡量 "更好" 的含义。

原文:

$q is is still useful for example for $q,all function. For requests, we probably should be using $http or wrappers around it.

I think one liner are good options with => and some transformations. But in the case of promises, we should always be prepared for chaining that's why I think we should always start a new line.

I think we should open a separate issue on () around parameters in arrow expressions.

I agree with the scout rule. That's why we are working on guidelines to a have an objective measure what 'better' means.

flaviotulino 2017-10-9
15

@PiotrSiatkowski $q. 一切都可以用诺言取代。你是说这个吗?

原文:

@PiotrSiatkowski $q.all can be replaced by Promise.all. Did you mean this?

jthomas1 2017-10-9
16

@flaviotulino很好, 在这种情况下, 因为巴贝尔 polyfills 的一切, 我非常赞成放弃 $q 的承诺, 而不是。

原文:

@flaviotulino Nice, well in that case since Babel polyfills everything I am very much in favour of dropping $q for Promise instead.

CERios 2017-10-9
17

我认为向承诺迈进是个好主意。伟大的呼喊@flaviotulino

你能用下面的代码提供一个例子吗?

constdefer=$q.defer();

halClient
    .$post(`${apiUrl}/api/v1/login/admin_sso/${companyId}`, {}, data)
    .then((login=> {
        constparams= { auth_token:login.auth_token };
        returnlogin.$get('administrator', params)
    })
    .then((admin=> {
        defer.resolve(admin);
    })
    .catch((err=> {
        defer.reject(err);
    });

returndefer.promise;
原文:

I think moving to Promise would be a good idea. Great shout @flaviotulino.

Can you provide an example using the code below?

const defer = $q.defer();

halClient
    .$post(`${apiUrl}/api/v1/login/admin_sso/${companyId}`, {}, data)
    .then((login) => {
        const params = { auth_token: login.auth_token };
        return login.$get('administrator', params)
    })
    .then((admin) => {
        defer.resolve(admin);
    })
    .catch((err) => {
        defer.reject(err);
    });

return defer.promise;
jthomas1 2017-10-9
18

它几乎完全相同, 除了创建一个延迟对象, 您 rerturn 一个 new Promise((resolve, reject) , 它将处理程序注入到您传递到构造函数的回调中

    returnnewPromise((resolvereject=> {
        halClient
            .$post(`${apiUrl}/api/v1/login/admin_sso/${companyId}`, {}, data)
            .then((login=> {
                constparams= { auth_token:login.auth_token };
                returnlogin.$get('administrator', params)
            })
            .then(resolve)
            .catch(reject);
    });
原文:

It's almost exactly the same except instead of creating a defer object you rerturn a new Promise((resolve, reject) which has the handlers injected into the callback you pass into the constructor

    return new Promise((resolve, reject) => {
        halClient
            .$post(`${apiUrl}/api/v1/login/admin_sso/${companyId}`, {}, data)
            .then((login) => {
                const params = { auth_token: login.auth_token };
                return login.$get('administrator', params)
            })
            .then(resolve)
            .catch(reject);
    });
piotrsiatkowski 2017-10-9
19

@flaviotulino是的, 当没有人使用它的时候, 很容易忘记它的存在。你是对的, 如果它有相同的功能, 它的确定。但是我们可以推迟 ES6 的诺言吗?延迟 API 不是那么直观, 但是当代码发疯的时候, 它是有用的。

原文:

@flaviotulino Yeah, when nobody is using it, it's easy to forget it exists. You are right, if it has the same functionality it's ok. But can we defer ES6 Promise? Deferring API is not so intuitive but it is useful sometimes when code goes mad.

jthomas1 2017-10-9
20

推迟是没有必要了, 但如果你真的想你可以做:

constmyPromise=newPromise((resolvereject=> {
// blah blah blah
})

return myPromise
原文:

Defer is not necessary anymore but if you really wanted to you could do:

const myPromise = new Promise((resolve, reject) => {
// blah blah blah
})

return myPromise
jthomas1 2017-10-9
21

更正: finally() 只适用于 $q 和蓝鸟, 而不是当地的承诺:(
您可以将另一个 .then.catch 之后假装我们有finally

原创评论:
另一点关于承诺, 我们可以利用的是, 他们有一个 .finally() 块可用, 以及一般清理像禁用加载纺纱等。

原文:

CORRECTION: finally() is only available in $q and bluebird not native Promises yet :(
You can put another .then after a .catch to pretend we have finally

Original comment:
Another point regarding promises that we can make use of is that they have a .finally() block available as well for general clean up like disabling loading spinners etc.

CERios 2017-10-9
22

所以我们同意:

  • 让我们逐步退出 $q
  • 用 ES6 的诺言。
  • 使用 .catch 而不是 error 回调。
  • 如果您需要 finally , 请使用 .then , 请在 .catch 出于上述原因解释之后。

我想这可能是第一次添加到我们的角风格指南。现在决定住在哪里?

原文:

So we're agreed:

  • Let's phase out $q.
  • Use ES6 Promise.
  • Use .catch instead of error callback.
  • If you need finally, use .then, after .catch for the reasons James explained above.

I guess this can be the first addition to our Angular Style Guide. Now to decide where that lives?

返回
发表文章
CERios
文章数
1
评论数
11
注册排名
60889