Javascript 获取数组中的每个项

Javascript 获取数组中的每个项,javascript,angular,promise,fetch,promise.all,Javascript,Angular,Promise,Fetch,Promise.all,所以我很确定这与承诺有关。所有的承诺或类似的东西,但我不确定怎么做。如果有人能帮我解决这个问题,我将不胜感激 注意:我试图映射的数组是一个对象数组,如果这很重要的话 const productsArray = this.cartProducts.map(product => fetch(`/api/products/getDetails/${product.clientId}`)) .then(res => res.json()) .then(d

所以我很确定这与承诺有关。所有的承诺或类似的东西,但我不确定怎么做。如果有人能帮我解决这个问题,我将不胜感激

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

const productsArray = this.cartProducts.map(product => 
      fetch(`/api/products/getDetails/${product.clientId}`))
      .then(res => res.json())
      .then(data => {
        console.log(data)
      })
我甚至不能启动这段代码,但我不确定我到底应该做什么

这是我在VisualStudio代码中的错误

property 'then' does not exist on type 'promise<response>[]'
类型“promise[]上不存在属性“then”
结果是promise,所以您需要使用

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

William Wang的答案非常好,但您可能希望使用async/await,如下所示:

constproductsarray=this.cartProducts.map(异步产品=>{
const res=wait fetch(`/api/products/getDetails/${product.clientId}`);
const data=res.json();
返回数据;
});
它可以简化为:

constproductsarray=this.cartProducts.map(异步产品=>{
return wait fetch(`/api/products/getDetails/${product.clientId}').json();
});

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

TL;DR:将数组中的每个项映射到一个获取调用,并将它们包装在Promise.all()周围

Promise.all(
this.cartProducts.map(p=>
fetch(`/api/products/getDetails/${p.clientId}`)。然后(res=>res.json())
)
).then(products=>console.log(products));
解释 返回一个a.k.a“我保证我将来会给你一个值”。到时候,该未来值将被解析并传递给
中的回调。然后(回调)
进行进一步处理。
.then()
的结果也是
承诺
,这意味着它们是可链接的

//返回承诺
获取(“…”)
//还愿
获取(“…”)。然后(res=>res.json())
//还返回未定义下一个解析值的承诺
获取(“…”)。然后(res=>res.json())。然后(()=>undefined)
因此,下面的代码将返回另一个
Promise
,其中解析的值是已解析的Javascript对象

fetch(“…”)。然后(res=>res.json())
将每个项映射到回调的结果,并在执行所有回调后返回一个新数组,在本例中是一个
Promise
数组

const promises=this.cartProducts.map(p=>
获取(“…”)。然后(res=>res.json()
);
调用map后,您将有一个等待解析的
Promise
列表。它们不包含如上所述从服务器获取的实际产品值。但您不需要promises,而是需要获取最终解析值的数组

这就是发挥作用的地方。它们是
Array.map()
的promise版本,它们使用
promise
API将每个
promise
映射到解析值

正因为如此,
Promise.all()
将在
promises
数组中的所有单个承诺都已解析之后解析另一个新的
Promise

//假设解析的值是Product
//承诺就是承诺
const promises=this.cartProducts.map(p=>
获取(“…”)。然后(res=>res.json()
);
承诺。所有(承诺)。然后(产品=>{
//产品就是产品[]。我们需要的实际价值
console.log(产品)
})

谢谢,这正是我要找的!它工作得很好,但是在它工作之前我遇到了一个400个stauts的错误…不确定为什么sync wait inside map()不能像预期的那样工作。你能详细说明一下吗?这是我的代码片段吗?还是一般情况下?我已经使用过几次这种模式,就我记忆所及,它一直工作。