![](/img/trans.png)
[英]How do I convert an Array of Promise to an Array of the values resolved from each Promise in vanilla JS?
[英]How do I convert a JS promise to another object
所以我有一个需要多次调用的异步 function 。 当然,我想使用 Promise.all
const promises = [];
ids.forEach((id) => {
stockoutPromises.push(
asyncFunc(id),
});
});
results[] = Promise.all(promises);
好的,没问题,但我怎么知道哪个 id 与哪个结果对应? 当然我可以再次遍历 arrays ,但是还有其他方法吗? 有没有一种方法可以创建一个 promise ,当解决后给我一个包含 id 和结果的 object ?
谢谢!
将.then
链接到asyncFunc
的调用上,以便生成的项不仅是asyncFunc
结果,而且是它和 object 中的 ID:
ids.forEach((id) => {
stockoutPromises.push(
asyncFunc(id).then(result => ({ id, result }))
);
});
但最好在循环中使用.map
而不是.push
:
const results = await Promise.all(
ids.map(id =>
asyncFunc(id).then(result => ({ id, result }))
)
);
const firstItem = results[0];
console.log(firstItem.result, firstItem.id);
Promise.all
的结果将按照它们最初的顺序(在承诺数组中)。 因此,您只需使用索引即可轻松重新关联:
// zip takes an array of keys, and an array of values, and creates an object: const zip = (a, b) => Object.fromEntries(a.map((k, i) => [k, b[i]])); // first id will resolve last, second will resolve next, etc. const ids = [0, 1, 2, 3, 4]; const promises = ids.map((i) => new Promise((resolve) => { setTimeout(() => resolve(i), 700 - (100 * i)); })); // but we still get the correct item in each spot, because of how // Promise.all works: (async () => { console.log(zip(ids, await Promise.all(promises))); })()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all :
返回值将按照 Promises 传递的顺序排列,无论完成顺序如何。
代替使用forEach ,使用map :
const promises = ids.map((id) => {
return asyncFunc(id)
});
const results = await Promise.all(promises);
map
将根据提供的 function 返回的内容返回一个新的对象数组。 在您的情况下,您正在调用asyncFunc
,我假设它返回 promise 本身。 因此,您可以直接返回map的结果,而无需推送到新的 Promise 数组。
此外,请确保“等待”对Promise.all
的调用;
您可以在这个 jsfiddle中查看它,它只是让asyncFunc
返回一个 promise ,它将ids
数组中的 id 加倍。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.