我正在使用co
来执行带有一堆http请求的生成器:
co(function *(){
// resolve multiple promises in parallel
var a = httpRequest(...);
var b = httpRequest(...);
var c = httpRequest(...);
var res = yield [a, b, c];
console.log(res);
}).catch(onerror);
有没有办法让我在每个 http 请求之间引入一秒钟的睡眠时间?谢谢。
是的,你可以。每个收益 - 使用 dilay 返回新的承诺(在承诺中 - 您必须根据 httpRequest 回调触发解析或拒绝)
以这种方式尝试
co(function *(){
var a = yield new Promise(function(resolve, reject){
setTimeout(function () {
//rosolve or reject this promise in callback of httpRequest();
}, 1000)
});
var b = yield new Promise(function(resolve, reject){
setTimeout(function () {
//rosolve or reject this promise in callback of httpRequest();
}, 1000)
});
var c = yield new Promise(function(resolve, reject){
setTimeout(function () {
//rosolve or reject this promise in callback of httpRequest();
}, 1000)
});
var res = [a, b, c];
console.log(res);
}).catch(onerror);