2016-11-13 108 views
5

我一直在玩一些链接功能集合的不同方式,似乎无法找到我特别喜欢的一个。以下是我最后决定的一个,但我仍然不热衷于此。链接承诺瀑布

有人可以建议一个更清洁和更简洁的模式?我不想选择Async.js或库。

[ 
    this.connectDatabase.bind(this), 
    this.connectServer.bind(this), 
    this.listen.bind(this) 
].reduce(
    (chain, fn) => { 
    let p = new Promise(fn); 
    chain.then(p); 
    return p; 
    }, 
    Promise.resolve() 
); 

Ps。任何其他技巧都比欢迎。

回答

5

上找到计算器这个解决方案如何,你可以链的承诺动态:

iterable.reduce((p, fn) => p.then(fn), Promise.resolve()) 

完整的职位是在这里:https://stackoverflow.com/a/30823708/4052701

+0

尼斯和清洁。谢谢! – ddibiase

+0

嗯,只是尝试了我的实现,看起来像它被简化了,因为它将承诺生成转移到单个函数中。想知道是否有什么可以完全避免。现在,这将通过=) – ddibiase

+0

这是美丽:) – robinmitra

2

什么ES7异步/ AWAIT? 您的代码中存在奇怪/旧的绑定(this),但不要与您的示例混淆。

async function x() { 
    try { 
     await this.connectDatabase.bind(this); 
     await this.connectServer.bind(this); 
     await this.listen.bind(this); 
    } catch(e) { 
     throw e; 
    } 
} 

或多个通用

async function() { 
    for (let item of yourArray) { 
     try { 
      await item.bind(this); //strange bind of your code. 
     } catch(e) { 
      throw e; 
     } 
    } 
} 
+0

是的,我更喜欢这样做。还没有触及ES7,害怕升级我们的代码库。绑定在那里,因为我没有学到一个新的/更好的模式来引用我的类中的类方法。在这种情况下,connectDatabase是我的类中的一个方法,然后使用对类中其他方法的引用。如果我没有将方法调用绑定到此,则会丢失它的上下文。建议? – ddibiase

+0

你能分享一些工作沙箱吗?如果我不想侦听connectServer是否失败,该怎么办? – codeofnode

+0

@codeofnode我通过添加try-catch来更新我的答案。你最后一个问题可以通过try-catch包围connectServer方法完成:try {await this.connectServer.bind(this);} catch(e){//不要继续}。如果您不想等待connectServer,则可以删除await。 –