Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

javascript - Execute native js promise in series

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 is useful only to have a new promise that merges a list of promise but it does not invoke them in a sequence.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
});

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());

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.


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
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...