3

所以我很确定这与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>[]'
4

3 回答 3

3

fetch()结果是承诺,所以你需要使用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()))
于 2020-12-22T13:24:32.560 回答
0

威廉王的回答非常好,但您可能想使用 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 将并行获取所有产品。

于 2020-12-22T13:45:17.703 回答
0

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()将解决另一个新的问题。Promisepromises

// 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)
})
于 2021-02-19T19:36:17.280 回答