2017-04-17 132 views
0

我試圖從for循環中的node.js服務器(使用'request'包)發送多個HTTP請求。Node.js - 使用請求在for循環中發送多個HTTP GET

這個想法是基本上有一個URL數組,每個發送一個HTTP get,並將響應存儲在一個名爲'responseArray'的數組中。

當我嘗試這個時,我得到'undefined',但我知道請求正在工作,如果我將它們記錄到for循環內的控制檯。

function apiCalls() { 
 

 
    var URLs = [‘URL1’, ‘URL2’, ‘URL3’]; 
 
    var responseArray = [] 
 
    for (var i = 0; i < URLs.length; i++) { 
 
    request({ 
 
     url: URLs[i], 
 
     method: 'GET', 
 
     headers: { 
 
     'Connection': 'close' 
 
     }, 
 
    }, function(error, response, body) { 
 
     if (error) { 
 
     console.log(error); 
 
     } else { 
 
     responseArray.push(String(response.body)); 
 
     console.log(responseArray) // this is showing me all the data in the array correctly 
 
     return responseArray; 
 
     } 
 
    }) //end request function 
 
    } //end for loop 
 
    console.log(responseArray) 
 
} //end apiCalls function 
 
apiCalls()

因此,在幾個不同的解決方案,在這裏尋找在堆棧溢出和elsehwere後,我嘗試使用的承諾。我從來沒有使用之前並根據這個離google example

承諾:

var apiCalls = new Promise(function(resolve, reject) { 
 
    var URLs = [‘URL1’, ‘URL2’, ‘URL3’]; 
 
    var responseArray = []; 
 
    for (var i = 0; i < URLs.length; i++) { 
 
    process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; 
 
    request({ 
 
     url: URLs[i], 
 
     method: 'GET', 
 
     headers: { 
 
     'Connection': 'close' 
 
     }, 
 
    }, function(error, response, body) { 
 
     if (error) { 
 
     console.log(error); 
 
     } else { 
 
     resolve(responseArray.push(String(response.body)) 
 
     } 
 
    }) //end request 
 

 
    } //end for loop 
 
}) 
 

 
apiCalls.then(function(result) { 
 
    console.log('this is calling the promise') 
 
    console.log(result) 
 
}, function(err) { 
 
    console.log(err) 
 
});

我總是得到一個空數組當我嘗試後的for循環日誌responseArray。或者 - 我得到「未定義」如果我試圖返回的數組賦值給一個變量,像這樣:

var gimmeAllResponses = apiCalls(); 
 
console.log(gimmeAllResponses); //returns 'undefined'

誰能告訴我我要去哪裏錯了嗎?如何在for循環完成後更新'responseArray'數據?

+1

你從哪裏得到'undefined'?在控制檯上?是不是'console.log(error)'語句,你認爲? – amn

回答

1

這是有點關閉,因爲這需要替代包,request-promise

你正在解決很多次。由於您使用的是Node.js,因此很可能ES6功能可用。使用Array.prototype.map()Promise.all()

var rp = require('request-promise'); 
var URLs = [‘URL1’, ‘URL2’, ‘URL3’]; 
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; 
var responseArray = Promise.all(URLs.map((url) => rp({ 
    uri: url, 
    method: 'GET', 
    headers: { 
    'Connection': 'close' 
    } 
}).then((error, response, body) => { 
    if (error) { 
     console.log(error); 
    } else { 
     return String(response.body); 
    } 
    })));