【问题标题】:Nodejs loop through array of urls in a synchronous wayNodejs以同步方式循环遍历url数组
【发布时间】:2020-10-20 14:18:19
【问题描述】:
我已经使用node 2 年了,但无法解决以下需求:
- 我有一个数组 ~ 50.000 参数
- 我需要遍历数组并发出 get 请求以始终使用添加了参数的相同 url
- 我需要将 url-call 的结果写回数组
- 需要一个一个来做,不能多线程调用api。
我确信有一个简单的解决方案,但我尝试的一切都没有让代码等待 get 请求返回。我知道在节点中同步做事不是我们应该做的事情,但在这种特殊情况下,在结果返回之前,该过程不会继续进行。
感谢任何提示
问候
【问题讨论】:
标签:
node.js
api
https
console-application
synchronous
【解决方案1】:
使用for 循环,使用执行返回承诺的GET 请求的方法(例如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);
});