在瀑布中链接许诺 [英] Chaining promises in a waterfall

查看:96
本文介绍了在瀑布中链接许诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在用几种不同的方式链接一组函数,但似乎找不到我特别喜欢的函数.以下是我确定的最后一个,但仍然不感兴趣.

I've been playing around with a few different ways of chaining a collection of functions and can't seem to find one I particularly like. The following is the last one I settled on but am still not keen on it.

有人可以提出一种更简洁,更简洁的模式吗?我不想选择Async.js或库.

Can someone suggest a cleaner and more concise pattern? I don't want to opt for Async.js or a library.

[
  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.任何其他提示都值得欢迎.

Ps. any other tips are more than welcomed.

推荐答案

在stackoverflow上找到了关于如何动态链接承诺的以下解决方案:

Found this solution on stackoverflow on how you can chain promises dynamically:

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

完整的帖子在这里: https://stackoverflow.com/a/30823708/4052701

这篇关于在瀑布中链接许诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆