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()
也是 aPromise
这意味着它们是可链接的。
// 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())
);
调用地图后,您将有一个Promise
等待解决的列表。它们不包含从服务器获取的实际产品价值,如上所述。但是您不想要承诺,您想要获得最终解析值的数组。
这就是Promise.all()
发挥作用的地方。它们是使用API将Array.map()
每个“映射”Promise
到已解析值的承诺版本。Promise
因此,在数组中的所有单个 Promise都已解决后,这Promise.all()
将解决另一个新的问题。Promise
promises
// 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)
})