gpt4 book ai didi

javascript - NodeJs : Multiple loop of HTTP requests execute simultaneously

转载 作者:行者123 更新时间:2023-12-01 00:37:30 25 4
gpt4 key购买 nike

nodejs multiple http requests in loop

根据上述问题,回答了如何使用一组工作正常的 url 执行一个 http 请求循环。但是我想要实现的是执行另一个 http 请求循环,该循环只能在之后完成第一个循环的完成(即,它应该等待 http 请求的第一个循环完成。

// Import http
var http = require('http');

// First URLs array
var urls_first = ["http://www.google.com", "http://www.example.com"];

// Second URLs array
var urls_second = ["http://www.yahoo.com", "http://www.fb.com"];

var responses = [];
var completed_requests = 0;

function performHTTP(array) {
for (i in urls_first) {
http.get(urls[i], function(res) {
responses.push(res);
completed_requests++;
if (completed_requests == urls.length) {
// All download done, process responses array
console.log(responses);
}
});
}
}

在上面的代码片段中,我添加了另一个 url 数组。我将 for 包装在一个函数内,以便每次调用时更改数组。由于我必须等待第一个循环完成,所以我尝试了 async/await ,如下所示.

async function callMethod() { 
await new Promise (resolve =>performHTTP(urls_first))) // Executing function with first array
await new Promise (resolve =>performHTTP(urls_second))) // Executing function with second array
}

但是在这种情况下,两个函数调用同时执行(即)它不会等待第一个数组执行完成。两个执行同时发生,我只需要在一个执行完成后才发生。

最佳答案

您需要在 Promise 中提出请求:

function request(url) {
return new Promise((resolve, reject) => {
http.get(url, function(res) {
// ... your code here ... //
// when your work is done, call resolve to make your promise done
resolve()
});
}
}

然后解决您的所有请求

// Batch all your firts request in parallel and wainting for all
await Promise.all(urls_first.map(url => request(url)));
// Do the same this second url
await Promise.all(urls_second.map(url => request(url)));

注意,此代码未经测试,可能包含一些错误,但主要原理在这里。

有关 Promise 的更多信息:https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise

关于javascript - NodeJs : Multiple loop of HTTP requests execute simultaneously,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57986216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com