我需要在node.js程序中执行未知数量的http请求,并且需要同步执行。只有当一个人得到响应,下一个请求才会被执行。我如何在JS中实现这一点?
--我与requset包()同步尝试
function HttpHandler(url){
request(url, function (error, response, body) {
...
})
}
HttpHandler("address-1")
HttpHandler("address-2")
...
HttpHandler("address-100")和异步的请求承诺:
async function HttpHandler(url){
const res = await request(url)
...
}
HttpHandler("address-1")
HttpHandler("address-2")
...
HttpHandler("address-100")他们都不工作。正如我说过的那样,我可以通过这个程序获得未知数量的http请求,这取决于最终用户。
有什么办法解决这个问题吗?
发布于 2021-01-22 23:36:28
使用got()库,而不是request()库,因为request()库已被废弃,不支持承诺。然后,您可以使用async/await和for循环依次对调用进行排序。
const got = require('got');
let urls = [...]; // some array of urls
async function processUrls(list) {
for (let url of urls) {
await got(url);
}
}
processUrls(urls).then(() => {
console.log("all done");
}).catch(err => {
console.log(err);
});您正在声明某种动态的URL列表,但是不会显示它是如何工作的,所以您必须自己找出逻辑的这一部分。我很乐意向大家展示如何解决这个问题,但你还没有给我们任何建议。
如果您想要一个可以定期添加项的队列,可以执行如下操作:
class sequencedQueue {
// fn is a function to call on each item in the queue
// if its asynchronous, it should return a promise
constructor(fn) {
this.queue = [];
this.processing = false;
this.fn = fn;
}
add(...items) {
this.queue.push(...items);
return this.run();
}
async run() {
// if not already processing, start processing
// because of await, this is not a blocking while loop
while (!this.processing && this.queue.length) {
try {
this.processing = true;
await this.fn(this.queue.shift());
} catch (e) {
// need to decide what to do upon error
// this is currently coded to just log the error and
// keep processing. To end processing, throw an error here.
console.log(e);
} finally {
this.processing = false;
}
}
}
}https://stackoverflow.com/questions/65853531
复制相似问题