私はノード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
[documentation](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)を読んで、どういうふうに見てください –