2014-12-05 63 views
1

我在使用承诺时发现了以下用例。我写的CoffeeScript的简洁但对于JavaScript开发人员的阅读要挺直向前使用promises的奉承调用:避免callbackception

getUserName().then (userName) -> 
    getRelatedCompany(userName).then (relatedCompany) -> 
    registerConnexion(userName, relatedCompany) 

在上述所有要求依赖于以前的上述结果。什么是解决这个问题,以得到这样的事情的正确方法:

getUserName().then (userName) -> 
    getRelatedCompany(userName) 
.then (relatedCompany) -> 
    # in that example, userName would be undefined here but there's less callbackception 
    registerConnexion(userName, relatedCompany) 

编辑:我使用的蓝鸟作为承诺库。

回答

1

您可以使用承诺为代表的数值代理:

username = getUserName() 
company = username.then(getRelatedCompany) 
// assuming good promise lib, otherwise shim .spread of nest once 
connexion = Promise.all([username, company]).spread(registerConnexion) 

在蓝鸟,这是更简单,并成为:

username = getUserName() 
company = username.then(getRelatedCompany) 
connexion = Promise.join(username, company, registerConnexion); 

由于.join是专为这种使用情况记在心里。

+0

我使用蓝鸟作为承诺库。我编辑了您的答案以解决拼写错误!谢谢! – AsTeR 2014-12-06 12:02:27

+0

@AsTeR编辑包含蓝鸟答案,即将更新。 – 2014-12-06 12:04:21

+0

我想你的StackExchange帐户描述是一种rickroll ...你让我;)! – AsTeR 2014-12-06 12:40:42