TL;DR:将数组中的每个项目映射到一个 fetch 调用并将它们包装在 Promise.all() 周围。
Promise.all(
this.cartProducts.map(p =>
fetch(`/api/products/getDetails/${p.clientId}`).then(res => res.json())
)
).then(products => console.log(products));
说明
fetch() 返回一个Promise 又名“我保证我会在未来给你一个价值”。时机成熟时,该未来值将解析并传递给.then(callback) 中的回调以进行进一步处理。 .then() 的结果也是 Promise,这意味着它们是可链接的。
// returns Promise
fetch('...')
// also returns Promise
fetch('...').then(res => res.json())
// also returns Promise where the next resolved value is undefined
fetch('...').then(res => res.json()).then(() => undefined)
所以下面的代码将返回另一个Promise,其中解析的值是一个解析的Javascript对象。
fetch('...').then(res => res.json())
Array.map() 将每个项目映射到回调的结果,并在所有回调执行后返回一个新数组,在本例中为Promise 的数组。
const promises = this.cartProducts.map(p =>
fetch("...").then(res => res.json())
);
调用map后,你会有Promise的列表等待解析。它们不包含从服务器获取的实际产品价值,如上所述。但是您不想要承诺,您想要获得最终解析值的数组。
这就是Promise.all() 发挥作用的地方。它们是 Array.map() 的承诺版本,它们使用 Promise API 将每个 Promise“映射”到解析的值。
因为Promise.all() 将在promises 数组中的所有 个单独的promise 都已解决之后再解决另一个新的Promise。
// assuming the resolved value is Product
// promises is Promise[]
const promises = this.cartProducts.map(p =>
fetch("...").then(res => res.json())
);
Promise.all(promises).then(products => {
// products is Product[]. The actual value we need
console.log(products)
})