kevdev
kevdev

Reputation: 187

Javascript Promises explicit functions vs. inline functions

I'm trying to understand the whacky world of javascript promises and came across this that I don't understand.

The first program is from a book explaining promise chaining and works just as you would think:

var Promise = require('promise');

function delay(time) {
    return new Promise( function(resolve,reject) {
        setTimeout( resolve, time ); 
    });
}

delay(1000) // step 1
    .then(function STEP2(){
        console.log( "step 2b (after 1000ms)" );
        return delay( 2000 );
    })
    .then(function STEP3(){
        console.log( "step 3b (after another 2000ms)" );
    })
    .then(function STEP4(){
        console.log( "step 4b (next Job)" );
        return delay( 5000 );
    })
    .then(function STEP5() {
        console.log( "step 5b (after another 5000ms)" );
    });

The console logs appear after the correct amount of delays.

NOW, in order to make this clearer in my own mind, I made the STEP functions explicitly so the program now looks like this:

var Promise = require('promise');

function delay(time) {
    return new Promise( function(resolve,reject){
        setTimeout( resolve, time );
    });
}
function STEP2() {
    console.log( "step 2 (after 1000ms)" );
    return delay( 2000 );
}
function STEP3() {
    console.log( "step 3 (after another 2000ms)" );    
}
function STEP4() {
    console.log( "step 4 (next Job)" );
    return delay( 5000 );
}
function STEP5() {
    console.log( "step 5 (after another 5000ms)" );
}

delay( 1000 ).then(STEP2()).then(STEP3()).then(STEP4()).then(STEP5());

But now all the console logs happen at once, the program delays 5000 ms and then exits. Can someone explain what is different (functionally) between the two examples above? Thank you.

Upvotes: 2

Views: 3482

Answers (1)

Anid Monsur
Anid Monsur

Reputation: 4538

In your first example, you are passing in a function. In your second example, you are passing in the result of the function since you included the () after the function name.

This is probably what you're looking to do:

delay( 1000 ).then(STEP2).then(STEP3).then(STEP4).then(STEP5);

Upvotes: 6

Related Questions