英文:
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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论