簡體   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