0
我使用節點js請求,向其他站點發出請求,所以請求是asyncronis函數,我需要在其全部執行後執行代碼完成的,但由於某種原因Promise.all()之前執行,這裏是代碼:Javascript Promise.all()在函數完成之前執行,node.js請求庫
// in this object I store request's promises
var tempObj = {};
for (var i = self.numberOfPaginations.length; i >= 1; i--) {
tempObj['request'+ i] = request('http://www.somewebsite.com/search/page='+i ,function (err,resp,body) {
// gets urls of listings
if (!err && resp.statusCode == 200) {
var $ = cheerio.load(body);
$('.title').each(function() {
self.urls.push($(this).attr('href'));
});
$('.info a').each(function() {
self.urls.push($(this).attr('href'));
});
// this log out puts the desired result
console.log(self.urls);
}
});
}
// this line of code pushes promises into array
Promise.all(Object.keys(tempObj).map(function (key) {return tempObj[key]})).then(function (argument) {
// this line of code executes before all the work in requests is done , however it should not!
console.log(self.urls);
});
,所以我的問題是,代碼Promise.all行()之前執行,因爲某些原因,
'request()'不返回承諾。 – SLaks
ops,比我應該創造一個承諾?我沒有在承諾 – Mikail
然後閱讀一些[文檔](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)的經驗,看看你怎麼去 –