Search code examples
javascriptpromisees6-promise

Javascript promise : is there any differences between anonymous and not anonymous callbacks?


const example = () => new Promise((resolve) => {
    resolve();
    console.log('1');
} )

example().then(console.log('3'))
console.log('2');

prints out 1 3 2

function create() {
    return new Promise(function(resolve, reject) {
        resolve();
        console.log('1');
    });
};

create().then(function() {
    console.log('3');
}, function() {
    console.log('4');
});

console.log('2');

prints out 1 2 3

I tested more than ten times each. But results are same. why this difference occurs?


Solution

  • then accepts a function as a parameter, not a function call such as console.log (which doesn't return a function, but returns undefined). So when you do

    example().then(console.log('3'))

    upon encountering the .then, it immediately evaluates console.log('3'), with the interpreter hoping/expecting for the function call to return a function, so that it can put the returned function into the .then chain. So, the console.log('3') gets printed immediately. But console.log returns undefined - it's not a function that goes into the asynchronous .then chain.

    It doesn't actually have anything to do with named vs anonymous functions. Your first snippet gives the .then a function as a parameter, but the second snippet gives the .then a console.log call as a parameter (which is evaluated immediately and returns undefined).

    Just by adding () => before the first snippet's console.log, you'll see that it behaves identically to the second snippet, by making the console.log call run asynchronously after the main thread is finished:

    const example = () => new Promise((resolve) => {
        resolve();
        console.log('1');
    } )
    
    example().then(() => console.log('3'))
    console.log('2');