首页 > 解决方案 > NodeJs:HTTP请求的多个循环同时执行

问题描述

nodejs循环中的多个http请求

根据上述问题,回答了如何使用一组 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
} 

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

标签: javascriptnode.jsasync-await

解决方案


您需要在 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


推荐阅读