Javascript 承诺的嵌套数组。我不明白什么?
我正在尝试使用一个API调用获取构建数据,然后使用该API调用进行另一个API调用。我不明白这些承诺是怎么起作用的。我的一系列承诺有什么错 这就是你要找的。具体而言,在该功能中:Javascript 承诺的嵌套数组。我不明白什么?,javascript,promise,Javascript,Promise,我正在尝试使用一个API调用获取构建数据,然后使用该API调用进行另一个API调用。我不明白这些承诺是怎么起作用的。我的一系列承诺有什么错 这就是你要找的。具体而言,在该功能中: function processAllFruits(fruits) { let newFruits = []; fruits.forEach(fruit => { processFruit(fruit).then(newFruit => { newFruits.push(new
function processAllFruits(fruits) {
let newFruits = [];
fruits.forEach(fruit => {
processFruit(fruit).then(newFruit => {
newFruits.push(newFruit);
})
})
return newFruits;
}
您正在同步返回newFruits
数组,而不是等待单个processFruit
承诺解析Promise.all()
function processAllFruits(fruits) {
let newFruits = fruits.map(processFruit)
return Promise.all(newFruits);
}
这是一个。这就是你要找的。具体而言,在该功能中:
function processAllFruits(fruits) {
let newFruits = [];
fruits.forEach(fruit => {
processFruit(fruit).then(newFruit => {
newFruits.push(newFruit);
})
})
return newFruits;
}
您正在同步返回newFruits
数组,而不是等待单个processFruit
承诺解析Promise.all()
function processAllFruits(fruits) {
let newFruits = fruits.map(processFruit)
return Promise.all(newFruits);
}
这是一个。你的过程所有的果实都应该等待所有的承诺。现在它是这样工作的:
1) 创造新的果实
2) 开始加工每种水果
3) 返回newFruits(仍然是空数组)
4) 完成处理并填充newFruits(因为它已经返回了,所以它不会做任何事情)您的processAllFruits应该等待所有承诺。现在它是这样工作的:
1) 创造新的果实
2) 开始加工每种水果
3) 返回newFruits(仍然是空数组)
4) 完成处理并填充newFruits(因为它已经返回了,所以不会做任何事情)