首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在JavaScript中执行同步HTTP请求

如何在JavaScript中执行同步HTTP请求
EN

Stack Overflow用户
提问于 2021-01-22 22:24:37
回答 1查看 8.2K关注 0票数 2

我需要在node.js程序中执行未知数量的http请求,并且需要同步执行。只有当一个人得到响应,下一个请求才会被执行。我如何在JS中实现这一点?

--我与requset包()同步尝试

代码语言:javascript
复制
function HttpHandler(url){

  request(url, function (error, response, body) {
     ...
  })

}

HttpHandler("address-1")
HttpHandler("address-2")
...
HttpHandler("address-100")

和异步的请求承诺:

代码语言:javascript
复制
async function HttpHandler(url){

  const res = await request(url)
  ...

}

HttpHandler("address-1")
HttpHandler("address-2")
...
HttpHandler("address-100")

他们都不工作。正如我说过的那样,我可以通过这个程序获得未知数量的http请求,这取决于最终用户。

有什么办法解决这个问题吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-22 23:36:28

使用got()库,而不是request()库,因为request()库已被废弃,不支持承诺。然后,您可以使用async/awaitfor循环依次对调用进行排序。

代码语言:javascript
复制
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列表,但是不会显示它是如何工作的,所以您必须自己找出逻辑的这一部分。我很乐意向大家展示如何解决这个问题,但你还没有给我们任何建议。

如果您想要一个可以定期添加项的队列,可以执行如下操作:

代码语言:javascript
复制
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;
            }
        }
    }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65853531

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档