gpt4 book ai didi

javascript - promise 链序

转载 作者:行者123 更新时间:2023-11-30 07:56:56 27 4
gpt4 key购买 nike

我使用下面的代码,有些东西让我有点困惑如果我输入 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com