使用promises设置javascript函数的顺序。
下面提到的代码给出以下输出,即 3 2 1
代替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();
});
我们如何设置此顺序。我要去哪里了。 .......... ....... ......
答案 0 :(得分:1)
您不是在等待一个人完成
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();
});