【问题标题】:Looping through a fetch operation in Node JS循环执行 Node JS 中的 fetch 操作
【发布时间】:2021-05-27 18:18:14
【问题描述】:

我正在尝试将 Json 对象的集合写入一个数组,同时在 Node JS 中循环执行 fetch 操作。我确定问题与它是异步操作有关,但不知道如何解决它。

这是我的代码:

    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。我可能错了。

提前致谢。

【问题讨论】:

    标签: node.js json node-fetch


    【解决方案1】:

    你可以这样做:

        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”来帮助等待所有的 Promises 解决并给出结果。

    注意:如果您的任何承诺将被拒绝,您将无法解决或拒绝后续的承诺。

    示例一在这里:

     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);
                })
    }

    【讨论】:

    • 谢谢。这正是我所需要的。
    猜你喜欢
    • 2019-12-07
    • 1970-01-01
    • 2014-04-10
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多