Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - How to do promise.all for array of array of promises?

I am trying to run array of functions parallel and when everybody finishes I want work on that result. I am using promises. Now, I can put all functions in an array and can do Promise.all(array of functions) But I have array like

[[promise1, promise2], [promise3,promise4], [promise5,promise6]],

where each promise is promisified function. Promise reference document says parameter in Promise.all should be an iterable object and my array is iterable. But it is not working for me. I think It is executing [promise1, promise2] as a promise but not individual promise.

Can anybody please help me how I can achieve it or is there any better way ?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You need to also call Promise.all for each array item:

const promise4all = Promise.all(
   promiseArray.map(function(innerPromiseArray) {
        return Promise.all(innerPromiseArray);
   })
);

Or directly:

// Fix: Promise.all.bind is required because it seems like Promise.all
// implementation relies on "this"
const promise4All = Promise.all(promiseArray.map(Promise.all.bind(Promise)))
// or
// const promise4All = Promise.all(promiseArray.map(p => Promise.all(p)))

This way the outer Promise.all gets the grouped promises in other Promise.all:

promise4all.then(function(promiseGroupResult) {
  // promiseGroupResult is the actual result of each promise group
  // and you'll be able to get each result this way: promiseGroupResult.somePropertyName
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...