簡體   English   中英

如何將 JS promise 轉換為另一個 object

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM