如何在使用Promise.AllSettled时在结果中获取Promise的引用。

huangapple go评论79阅读模式
英文:

How to have a reference of the Promise in the results using Promise.AllSettled

问题

我有一个关于JS和Promise AllSettled的愚蠢问题。

const ids = [1, 10, 33, 40];

const promises = ids.map(id => getObjectById(id))

const result = await Promise.allSettled(promises)

result.map(item => {
  if (item.status === 'fulfilled') {
    console.log(value)
    // {
    //   key: value
    //   key1: value2
    //   key3: [
    //     ...
    //   ]
    // }

    // 我如何在这里为每个promise保留ids数组的引用
  }
})
我有一个函数数组,用于使用ID进行API调用以获取其对应的对象。但在结果中,没有ID的引用。所以我想知道是否有JS方法来处理这个问题,以及处理它的最高性能方式是什么。我想要保留生成该结果的promise的引用。
英文:

I've a stupid question about JS and Promise AllSettled.

const ids = [1,10,33,40];

const promises = ids.map(id => getObjectById(id))

const result = await Promise.allSettled(promises)

result.map(item => {
  if (item.status === 'fullfiled') {
    console.log(value)
    // {
    //   key: value
    //   key1: value2
    //   key3: [
    //     ...
    //   ]
    // }

    // how can I have a referecen of the ids array here for each promise
  }
})

I have an array of functions that make api call using an id to fetch its correspondent object. But, in the results, there is reference of the ID. So I was wondering if is there a JS way to handle this and what would be the most perfomance way to handle it. I want to have the a reference of the promise that generated that result.

答案1

得分: 2

你需要在最终的 Promise 中保留这些值:

const result = await Promise.allSettled([
  Promise.all([1, getObjectById(1)]),
  //...
])

然后在结果中:

results.map(([id, item]) => {...});

注意,因为你使用了 Promise.allSettled,你的 item 可能是一个错误!

英文:

You need to preserve those values in the final Promise:

const result = await Promise.allSettled([
  Promise.all([1, getObjectById(1)]),
  //...
])

and then in the results:

results.map(([id, item]) => {...});

NOTE since you're using Promise.allSettled, your item could be an error!

huangapple
  • 本文由 发表于 2023年8月10日 20:47:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76875878.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定