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

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

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

问题

  1. 我有一个关于JSPromise AllSettled的愚蠢问题。
  2. const ids = [1, 10, 33, 40];
  3. const promises = ids.map(id => getObjectById(id))
  4. const result = await Promise.allSettled(promises)
  5. result.map(item => {
  6. if (item.status === 'fulfilled') {
  7. console.log(value)
  8. // {
  9. // key: value
  10. // key1: value2
  11. // key3: [
  12. // ...
  13. // ]
  14. // }
  15. // 我如何在这里为每个promise保留ids数组的引用
  16. }
  17. })
  18. 我有一个函数数组,用于使用ID进行API调用以获取其对应的对象。但在结果中,没有ID的引用。所以我想知道是否有JS方法来处理这个问题,以及处理它的最高性能方式是什么。我想要保留生成该结果的promise的引用。
英文:

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

  1. const ids = [1,10,33,40];
  2. const promises = ids.map(id => getObjectById(id))
  3. const result = await Promise.allSettled(promises)
  4. result.map(item => {
  5. if (item.status === 'fullfiled') {
  6. console.log(value)
  7. // {
  8. // key: value
  9. // key1: value2
  10. // key3: [
  11. // ...
  12. // ]
  13. // }
  14. // how can I have a referecen of the ids array here for each promise
  15. }
  16. })

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 中保留这些值:

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

然后在结果中:

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

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

英文:

You need to preserve those values in the final Promise:

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

and then in the results:

  1. 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:

确定