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)的经验,看看你怎么去 –