在系列中执行本机js promise [英] Execute native js promise in series

查看:108
本文介绍了在系列中执行本机js promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须为数组中的每个项目调用一些异步任务的承诺,但我想连续执行这些。

I have to call a promise for some async task for each item in an array but I would like to execute these serially.

Promise.all仅对有一个新的承诺,合并一个承诺列表,但它不会按顺序调用它们。

Promise.all is useful only to have a new promise that merges a list of promise but it does not invoke them in a sequence.

如何使用标准的promise api实现这一点,而不需要像第三方库那样Q,bluebird ....

How can I achieve this using standard promise api without third-party libraries like Q, bluebird....

推荐答案

使用 .then()带有一个返回另一个promise的回调。所以,假设你有三个函数a,b和c都返回一个promise。你可以像这样链接它们(按顺序执行):

You chain promises using .then() with a callback that returns another promise. So, let's say you have three functions a, b and c that all return a promise. You can chain them (execute in sequence) like this:

a().then(b).then(c).then(function(result) {
   // all are done here
});

如果您正在处理数组并且您有一个承诺返回函数 myFunc 你想要为数组中的每个项目调用,你可以使用标准的数组设计模式和承诺 .reduce()来走通过数组一次一个项目如下:

If you are processing an array and you have a promise-returning function myFunc that you want to call for each item in the array, you can use a standard design pattern for arrays and promises with .reduce() to walk through the array one item at a time like this:

var items = [...];

items.reduce(function(p, item) {
    return p.then(function() {
        return myFunc(item);
    });
}, Promise.resolve());

事实证明这只是链接了一堆 .then( )第一个例子中的处理程序,但使用 .reduce()的结构为你走数组。

As it turns out this is really just chaining a bunch of .then() handlers like in the first example, but using the structure of .reduce() to walk the array for you.

从ES2017开始,你也可以使用async / await串行处理这样的数组:

Starting with ES2017, you can also use async/await to serially process an array like this:

async function processArray(arr) {
    for (let item of arr) {
        let result = await somePromiseReturningFunc(item);
        // do something with result here before
        // going on to next array item
    }
    return someFinalResult;
}

processArray(someArray).then(result => {
    // done processing array here
}).catch(err => {
    // handle error here
});

这篇关于在系列中执行本机js promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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