简体   繁体   中英

Node.js Promise Chain not firing in desired order

I created a simple example of a Promise chain. My goal is to fire the 4 functions below to get the output in Order. ie 1 2 3 4.

function WriteOne()
{
    return new Promise(function(resolve, reject)
    {
        console.log("1");
        resolve("true");
    })    
}

function WriteTwo()
{
    return new Promise(function(resolve, reject)
    {
        setTimeout(function(){console.log("2");}, 3000);
        resolve("true");
    })    
}

function WriteThree()
{
    return new Promise(function(resolve, reject)
    {
        setTimeout(function(){console.log("3");}, 1000);
        resolve("true");
    })
}

function WriteFour()
{
    return new Promise(function(resolve, reject)
    {
        console.log("4");
        resolve("true");
    }) 
}

WriteOne().then(WriteTwo).then(WriteThree).then(WriteFour);

When I execute them, they are firing in this order:

1 4 3 2

What am I doing wrong here?

You need to resolve inside setTimeout callback

 function WriteOne() { return new Promise(function (resolve, reject) { console.log("1"); resolve("true"); }); } function WriteTwo() { return new Promise(function (resolve, reject) { setTimeout(function () { console.log("2"); resolve("true"); }, 3000); }); } function WriteThree() { return new Promise(function (resolve, reject) { setTimeout(function () { console.log("3"); resolve("true"); }, 1000); }); } function WriteFour() { return new Promise(function (resolve, reject) { console.log("4"); resolve("true"); }); } WriteOne().then(WriteTwo).then(WriteThree).then(WriteFour); 

Nothing wrong here, here what's happening:

// t=0s
writeOne()
// 1 is logged
// promise is resolved
.then(writeTwo)
// in 3s, 2 will be logged
// promise is resolved
.then(writeThree)
// in 1s, 3 will be logged
// promise is resolved
.then(writeFour)
// 4 is logged

// t=1s
// 3 is logged

// t=3s
// 2 is logged

Thus the output.

To get the result you're expecting, resolve the promise inside the setTimeout.

resolve("true") is called before the console.log() because it's outside the setTimeout() .

Since WriteOne() and WriteFour() have no timeout, "1" and "4" appear first. Then "3" 1 second later, Then 2.

You have to put resolve("true"); inside setTimeout() in order to have them appear... in order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM