最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JS: asyncawait for multiple promises - Stack Overflow

programmeradmin3浏览0评论

If I have promise running synchronously, how do I want for both of them to finish? Doesn't await only work for a single Promise?

async function testing() {
  let promise1 = new Promise((resolve, reject) => {
    setTimeout(() => resolve("one"), 1000)
  });

  let promise2 = new Promise((resolve, reject) => {
    setTimeout(() => resolve("two"), 1000)
  });


  // how do I await both of these?
}

If I have promise running synchronously, how do I want for both of them to finish? Doesn't await only work for a single Promise?

async function testing() {
  let promise1 = new Promise((resolve, reject) => {
    setTimeout(() => resolve("one"), 1000)
  });

  let promise2 = new Promise((resolve, reject) => {
    setTimeout(() => resolve("two"), 1000)
  });


  // how do I await both of these?
}
Share Improve this question asked Dec 6, 2020 at 5:59 MarketMan39MarketMan39 2082 silver badges8 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 13

You can use Promise.all to wait for both of them at once

const [result1, result2] = await Promise.all([promise1, promise2]))

If you want to resolve all promises then you can do two things which are Promise.allSettled() or Promise.all(). So based on your need, choose one.

The Promise.allSettled() method returns a promise that resolves after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the oute of each promise.

Promise.allSettled([
    Promise.resolve('promise1'),
    Promise.reject('promise2')
]).then(console.log)

It is typically used when you have multiple asynchronous tasks that are not dependent on one another to plete successfully, or you'd always like to know the result of each promise.

In parison, the Promise returned by Promise.all() may be more appropriate if the tasks are dependent on each other / if you'd like to immediately reject upon any of them rejecting.

Promise.all([Promise1, Promise2])
 .then(result) => {
   console.log(result)
 })
 .catch(error => console.log(`Error in promises ${error}`))

Reference: https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled

You can use promise.all or promise.allSettled

If your use case is like if any one of the request fails then operation needed to be fail means then its good to use promise.all

If you need to keep waiting for all, regardless of any in between request fails or not then you need to use promise.allSettled.

But both of these wont ensure serializability. If you need to ensure serializable i would prefer to use for await loop and use promise.resolve inside it.

发布评论

评论列表(0)

  1. 暂无评论