串行执行返回promise的函数 [英] Serial execution of functions returning promises

查看:81
本文介绍了串行执行返回promise的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

凭借ES2016,我们现在有了承诺,这很棒。不幸的是,该功能非常简约,并且没有像async包中可用的系列或瀑布那样。
如果有一个为promises提供此功能的软件包,或者人们通常如何处理这些用例?

With ES2016 we now have promises and that's great. Unfortunately the functionality is very minimalistic and there is nothing like the series or waterfall as available in the async package. If there a package providing this functionality for promises or how do people typically deal with those use cases?

推荐答案

To串行执行一系列函数返回你可以使用的promise Array.prototype.reduce

To serially execute an array of functions returning promises you can use Array.prototype.reduce:

let final = functions.reduce((prev, f) => prev.then(f), Promise.resolve());

初始参数 Promise.resolve()是否为promises链设定种子,否则(如果传递的数组只包含一个函数), .reduce 回调永远不会被调用。

The "initial" argument Promise.resolve() is there to seed the chain of promises, since otherwise (if passed an array containing only a single function) the .reduce callback never gets called.

这篇关于串行执行返回promise的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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