all内部的诺言完成后再解决

all内部的诺言完成后再解决

本文介绍了等待Promise.all内部的诺言完成后再解决的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Promise.all,它可以执行映射到数组输入上的异步函数(如果它不为null),然后将数据解析为先前定义的Promise:

I have a Promise.all that executes asynchronous functions mapped on an array input if it's not null and then resolve data to a previously defined Promise:

Promise.all((inputs || []).map(input => {
  return new Promise((resolve, reject) => {
    someAsyncFunc(input)
    .then(intermediateOutput => {
      someOtherAsyncFunc(intermediateOutput )
      .then(output => {
        return Promise.resolve(output )
      })
      .catch(reason=> {
        return Promise.reject(reason)
      })
    })
    .catch(reason => {
      return Promise.reject(reason);
    })
  })
  .then(outputs => {
    resolve(outputs)
  })
  .catch(reason => {
    reject(reason)
  })
}))

在someAsyncFunc完成工作之前,我只能得到空的输出。如何使Promise.all等待内部的诺言完成异步工作?

I only get empty outputs before even someAsyncFunc finishes its work. How can make Promise.all wait for the promises inside to finish their asynchronous work ?

推荐答案

请参阅jfriend的评论。

See jfriend's comment.

someAsyncFunc someOtherAsyncFunc 是可以正确返回promise
的函数,例如 return new Promise(/ *。 .. * /);

someAsyncFunc and someOtherAsyncFunc are function that properly return a promisewith something like return new Promise(/*...*/);

这没用:

.then(output => {
  return Promise.resolve(output )
})

阅读Promise文档

read the Promise documentation

相同

.catch(reason=> {
  return Promise.reject(reason)
})

该承诺已经被拒绝,您不需要捉住并拒绝自己

the Promise is already rejecting, you don't need to catch and reject yourself

确保承诺是可链接的,您需要返回承诺

to make sure Promises are chainable you need to return the Promise

// ...
return new Promise((resolve, reject) => {
  if(inputs == null)
    resolve([]);
  else {
    Promise.all(inputs.map(input => {
      return someAsyncFunc(input)
        .then(someOtherAsyncFunc)
    }))
      .then(resolve)
      .catch(reject)
  }
});

请注意,我宁愿不要为Promise做麻烦,因为它们全部是内联的,它增加了视觉上的混乱: p>

note I would rather not make the arry for Promise.all inline, it adds visual clutter:

return new Promise((resolve, reject) => {
  if(inputs == null)
    resolve([]);
  else {
    const myPromises = inputs.map(input => {
      return someAsyncFunc(input)
        .then(someOtherAsyncFunc)
    });
    Promise.all(myPromises)
      .then(resolve)
      .catch(reject)
  }
});

如果您犯了其他错误,它可能仍然会失败。

it may still fail if you made other mistakes.

这篇关于等待Promise.all内部的诺言完成后再解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 11:24