微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Node JS 中循环执行 fetch 操作

如何解决在 Node JS 中循环执行 fetch 操作

我正在尝试将一组 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);
            })
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。