[英]NodeJS, request-promises are not waiting for each other
因此,我已將問題分解成一個簡單的代碼段。
我希望otherRequestes
等待我的firstRequests
,但是以某種方式,這是行不通的。 firstRequested
從未等待
const rp = require('request-promise');
const firstRequest = () => {
return rp('http://www.google.com')
.then(function(htmlString) {
console.log('in then of firstrequest');
})
.catch(function(err) {
console.log('catch', err);
});
}
laterRequest = (i) => {
return rp('http://www.google.com')
.then(function(htmlString) {
console.log('in then' + i);
})
.catch(function(err) {
console.log('catch', err);
});
}
const requests = [];
for (let i = 0; i < 10; i += 1) {
requests.push(laterRequest(i));
}
firstRequest().then(() => {
Promise.all(requests).then(() => {
console.log('all promises returned');
});
});
所以我想要的輸出是“在firstrequest中”,在那之后輸出應該是latestRequest,我不在乎它們的順序。
但是當我當前運行它時,我的輸出如下所示, firstRequest
隨機出現在輸出中的某個位置:
in then0
in then5
in then2
in then3
in then1
in then8
in then4
in then6
in then9
in then7
in then of firstrequest
all promises returned
當您執行for
循環時,您將在調用第一個承諾之前調用所有其他promise。 調用您的第一個承諾,然后在.then()
(當您知道其完成時)開始調用其他承諾。
firstRequest().then(() => {
const requests = [];
for (let i = 0; i < 10; i += 1) {
requests.push(laterRequest(i));
}
return Promise.all(requests).then(() => {
console.log('all promises returned');
});
});
您的firstRequest
沒有返回承諾。 您已經通過在函數中附加.then
來將解析處理程序附加到它。
您可以使用幾種不同的方法來構造此代碼,但是似乎您希望在每個承諾成功或失敗時都將一些內容記錄到控制台,因此您可以執行以下操作:
const firstRequest = () => {
return new Promise((resolve, reject) => { // actually returns a promise now
rp('http://www.google.com')
.then(function(htmlString) {
console.log('in then of firstrequest');
resolve(htmlString); // promise resolves (i.e. calles its `.then` function)
})
.catch(function(err) {
console.log('catch', err);
reject(err); // promise rejects (calles the `.catch`)
});
})
}
const laterRequest = (i) => {
return new Promise((resolve, reject) => {
rp('http://www.google.com')
.then(function(htmlString) {
console.log('in then' + i);
resolve(htmlString);
})
.catch(function(err) {
console.log('catch', err);
reject(err);
});
})
}
const requests = [];
for (let i = 0; i < 10; i += 1) {
requests.push(laterRequest(i));
}
firstRequest().then(() => {
Promise.all(requests).then(() => {
console.log('all promises returned');
});
});
答案較短
您也可以跳過重復then
s和catch
es,而直接返回rp
的promise:
const firstRequest = () => rp('http://www.google.com');
const laterRequest = (i) => rp('http://www.google.com');
firstRequest().then(() => {
const requests = [];
for (let i = 0; i < 10; i += 1) {
requests.push(laterRequest(i));
}
Promise.all(requests).then(() => {
console.log('all promises returned');
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.