【发布时间】:2017-10-24 14:50:21
【问题描述】:
所以我将我的问题分解为一个简单的代码 sn-p。
我希望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');
});
});
所以我想要的输出是“in then of firstrequest”之后的输出应该是后来的请求,我不在乎他们的顺序。
但是当我当前运行它时,我的输出如下,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
【问题讨论】:
-
问题是,您与 firstRequest 并行启动其他 10 个请求 - 您需要在 firstRequest 中使用 for 循环。然后
标签: javascript node.js promise request