问题描述
我正在尝试将一组 Json 对象写入数组,同时循环执行 Node JS 中的提取操作。我确定这个问题与异步操作有关,但不知道如何绕过它。
这是我的代码:
for (const car of carFilter) {
const carjson = fetch(modelUrl + car,settings)
.then(res => res.json())
.then((json.data.trim));
carData.push(carjson);
}
console.log(carData);
我从 console.log 得到的信息是:
Promise { <pending> },Promise { <pending> },... etc
我认为这意味着我正在尝试在将数据推送到数组之前执行 console.log。我可能错了。
提前致谢。
解决方法
你可以这样做:
const promises = [];
for (const car of carFilter) {
const carJson = fetch(modelUrl + car,settings)
promises.push(carJson);
}
Promise.all(promises)
.then((values) => {
console.log(values); // will be in same order they are called
console.log(values[0]); // will be an Array
})
.catch( e => console.log(e));
因此,当我们调用异步操作时,它会返回一个 Promise(在本例中)。我们将所有 promise 推送到一个数组中,并且可以使用“Promises.all”来帮助等待所有 promise 解决并给出结果。
注意:如果您的任何承诺被拒绝,您将无法获得后续承诺的解决或拒绝。
示例在这里:
const promises = [];
for (let i = 0; i < 10; i++) {
const carJson = promiseCall(); //any promise call
promises.push(carJson);
}
Promise.all(promises)
.then((values) => {
console.log(values); // will be in same order they are called
})
.catch( e => console.log(e));
function promiseCall () {
return new Promise((res,rej) => {
setTimeout(()=> {
res(true);
},1000);
})
}