获取数组中的每个项目 说明

问题描述

所以我很确定这与 Promise.all 或类似的东西有关,但我不确定如何去做。如果有人可以帮助我解决代码,我将不胜感激。

注意:如果重要的话,我要映射的数组是一个对象数组

const productsArray = this.cartProducts.map(product => 
      fetch(`/api/products/getDetails/${product.clientId}`))
      .then(res => res.json())
      .then(data => {
        console.log(data)
      })

我什至无法启动此代码,但我不确定我应该做什么...

这是我在 Visual Studio 代码中的错误

property 'then' does not exist on type 'promise<response>[]'

解决方法

fetch() 结果是 promise,所以你需要使用 Promise.all()

const promises = await Promise.all(this.cartProducts.map(product => fetch(`/api/products/getDetails/${product.clientId}`))
const productsArray = await Promise.all(promises.map(p => p.json()))
,

William Wang 的回答非常好,但您可能想使用 async/await 来喜欢这个:

const productsArray = this.cartProducts.map(async product => {
      const res = await fetch(`/api/products/getDetails/${product.clientId}`);
      const data = res.json();
      return data;
});

可以简化为:

const productsArray = this.cartProducts.map(async product => {
      return await fetch(`/api/products/getDetails/${product.clientId}`).json();
});

但是请注意,这种模式将比使用 Promise.all 模式更“同步”,因为每个产品只会在前一个被获取后才会被获取。 Promise.all 将并行获取所有产品。

,

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() 数组中的所有单个承诺之后,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)
})