gpt4 book ai didi

javascript - 使用 Promises 设置 Sequence to Javascript 函数

转载 作者:行者123 更新时间:2023-12-03 00:54:44 25 4
gpt4 key购买 nike

使用 Promise 设置 javascript 函数的序列。

下面提到的代码给出以下输出,即321

而不是 1 3 2

    let functionOne = function ()
{
return new Promise(function(resolve,reject){
One();
resolve();
});
}

let functionTwo = function ()
{
return new Promise(function(resolve,reject){
Two();
resolve();
});
}

let functionThree = function ()
{
return new Promise(function(resolve,reject){
Three();
resolve();
});
}



function One()
{
setTimeout(function() {
console.log(1);
},3000);

}
function Two()
{

console.log(2);
}

function Three()
{

console.log(3);
}

functionOne().then(function(){
return functionThree();
}).then(function(){
return functionTwo();
});

我们如何设置这个顺序。我哪里出错了。…………………….......

最佳答案

你没有等待 One 完成

let functionOne = function () { // no need for a new Promise here, since One returns a Promise
return One();
}
let functionTwo = function () {
return new Promise(function(resolve,reject){
Two();
resolve();
});
}

let functionThree = function () {
return new Promise(function(resolve,reject){
Three();
resolve();
});
}

function One() { // return a Promise to wait for
return new Promise(function(resolve) {
setTimeout(function() {
console.log(1);
resolve();
}, 3000);
});
}

function Two() {
console.log(2);
}

function Three() {
console.log(3);
}

functionOne().then(function(){
return functionThree();
}).then(function(){
return functionTwo();
});

关于javascript - 使用 Promises 设置 Sequence to Javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52886507/

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