Nodejs以同步方式循环遍历url数组

Nodejs loop through array of urls in a synchronous way

我已经使用 node 2 年了,但无法解决以下需求:

我确信有一个简单的解决方案,但我尝试的一切都没有让代码等待对 return 的获取请求。我知道在节点中同步做事不是我们应该做的事情,但在这种特殊情况下,根据设计,在结果返回之前,该过程不应继续。

感谢任何提示

此致

使用 for 循环,使用 GET 请求 returns 承诺(例如 got() 库)的方法,然后使用 await 来暂停 for 循环,直到您回复。

const got = require('got');
const yourArray = [...];

async function run() {
    for (let [index, item] of yourArray.entries()) {
        try {
            let result = await got(item.url);
            // do something with the result
        } catch(e) {
            // either handle the error here or throw to stop further processing
        }
    }
}

run().then(() => {
    console.log("all done");
}).catch(err => {
    console.log(err);
});