3

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

2
  • then expects a function as it's argument(s) - not the result of running a function! Commented Feb 14, 2017 at 23:55
  • You code doesn't produce ANY output - it's syntactically wrong in every function and has unreachable code in first, second and third - and none of first, second or third would ever resolve either ... more wrong than right in the code Commented Feb 14, 2017 at 23:58

1 Answer 1

4

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)
    });
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.