Search code examples
javascriptnode.jspromisees6-promise

How to execute functions sequentially using Node Js Promise?


I'm new to Node js Promise I'm not sure whether I'm using the Promise correctly or not so here is my code.

function print(){

    first('first')
    .then(second('second'))
    .then(third('third'));
}

function first(a){
    return new Promise((resolve, reject) => {
        var res1 = function (){
            resolve(a);
        }    
    });
    console.log(a);
}

function second(b){
    return new Promise((resolve, reject) => {
        var res1 = function (){
            resolve(b);
        }    
    });
    setTimeout(() => {
        console.log(b);
    }, 2000);
}

function third(c){
    return new Promise((resolve, reject) => {
        var res1 = function (){
            resolve(c);
        }    
    });
    console.log(c);
}

My desired output is

first
second
third

Instead what I get is

first
third
//after two seconds
second

I'm missing something but I can't figure it out please explain me


Solution

  • To get the expected behaviour, you need to resolve inside of the timeout (next to the console log). You also cannot pass arguments into promise chain functions since they need to accept the promise from the previous thennable.

    A working snippet is below:

    print();
    
    function print(){
        first('first')
        .then(second)
        .then(third);
    }
    
    function first(a){
        return new Promise((resolve, reject) => {
        		console.log(a);
            resolve(a);  
        });
    }
    
    function second(b){
        return new Promise((resolve, reject) => {
          setTimeout(() => {
          		console.log("second");
          		resolve(b);
          }, 2000);  
        });
    
    }
    
    function third(c){
        return new Promise((resolve, reject) => {
        		console.log("third"); 
            resolve(c)
        });
    }