我使用下面的代码,有些东西让我有点困惑 如果我输入 1000 毫秒的超时时间,我会看到 promise 以正确的顺序调用 但是如果我把它改成下面的
This is step 3
This is step 2
This is step 1
我猜这是因为当函数被resolved
然后他继续执行next function
我是正确的吗?如果这是真的,我该如何做这个链,当第一个完成时 then
他继续第二个等等但不使用 promise hell :-)
https://jsfiddle.net/2yym400j/
var step1 = function(ms) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log("This is step 1");
resolve();
}, ms);
})
}
var step2 = function(ms) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log("This is step 2");
resolve();
}, ms);
})
};
var step3 = function(ms) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log("This is step 3");
resolve();
}, ms);
})
};
step1(500)
.then(step2(300))
.then(step3(200))
.catch(function(err) {
console.log(err);
});
最佳答案
只传递一个函数而不是步骤的结果。
step1(500)
.then(function() { return step2(300); })
.then(function() { return step3(200); })
.catch(function(err) {
console.log(err);
});
如果没有这个,您只是调用每个步骤而不会“阻塞”上一个步骤来解决。
关于javascript - promise 链序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37641867/