繁体   English   中英

NodeJ:HTTP请求的多个循环同时执行

[英]NodeJs : Multiple loop of HTTP requests execute simultaneously

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
} 

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

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

查看第一个完成后如何使用.then ()调用第二个performHttp。

您可以使用eachSeries调用服务。

https://www.npmjs.com/package/async-series

series([
  function(done) {
    console.log('First API Call here')
    done() // if you will pass err in callback it will be caught in error section.
  },
  function(done) {
    console.log('second API call here')
    done()
  },
  function(done) {
    // handle success here
  }
], function(err) {
  console.log(err.message) // "another thing"
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM