Needles to say I am doing something wrong. I need some help figuring out what it is.
Consider the following code (a simplified version of my problem):
function testTimer(time, msg,resolve){
console.log(arguments.callee.name);
window.setTimeout(
function() {
console.log("MSG:", msg);
if(resolve !== undefined)
resolve(1);
}, time * 1000);
}
new Promise(function(resolve, reject) {
testTimer(1, 'ONE', resolve);
}).then(function(resolved){testTimer(9, 'TWO');}, function(rejected){alert("Rejected!", reject)})
.then(function(resolved){testTimer(1, 'THREE'); }, function(rejected){alert("Rejected!", reject)});
The expected output is:
ONE
TWO
THREE
Instead since the first then requires 9 seconds to execute and the second then requires 1 second to execute I get:
ONE
THREE
TWO
The question is simple: How can I get the then's to wait for eachother ?
Thanks!
答案 0 :(得分:0)
您需要返回仅在超时后解决的承诺:
function testTimer(time, msg,resolve) {
console.log(arguments.callee.name);
window.setTimeout(function() {
console.log("MSG:", msg);
if(resolve !== undefined) {
resolve(1);
}
}, time * 1000);
}
new Promise(function(resolve, reject) {
testTimer(1, 'ONE', resolve);
}).then(
function(resolved){
// here we return a promise - that is resolved by testTimer
// function. Notice that I'm passing a resolve function into it
return new Promise(function(resolve) {
testTimer(9, 'TWO', resolve);
});
},
function(rejected){
alert("Rejected!", reject)
}
)
.then(
function(resolved){testTimer(1, 'THREE'); },
function(rejected){alert("Rejected!", reject)}
);
它是如何工作的:testTimer
函数已经定义了它 - 接受一个回调作为第三个参数,它将在触发定时器后被调用。我们使用它来解决我们在第二步中设置的嵌套承诺。因此,第三步仅在第二步解决后发生,这发生在计时器中,因此订单保持预期。