Order of execution in a Promise

2

I have the following code:

const execute = function() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
             console.info('Iniciou');
             resolve('Executando');
             console.info('Finalizou');
        }, 1000);
    })
    .then((data) => {
        console.info(data);
    })
    .catch((err) => {
        console.error(err);
    });
};

execute();

As you can see the execution of this code generates as output:

// Iniciou
// Finalizou
// Executando

I honestly have no idea why this happens, if anyone can clarify this doubt.

    
asked by anonymous 15.11.2018 / 03:26

1 answer

2

In a promise when you return the result 'resolves' what you are doing and sends the result to the 'then' being asynchronous this action and executing the functionality afterwards resolves immediately.

The right thing to do resolves the latter:

const execute = function() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
             console.info('Iniciou');
             console.info('Executando');
             resolve('Finalizou');
        }, 1000);
    })
    .then((data) => {
        console.info(data);
    })
    .catch((err) => {
        console.error(err);
    });
};

execute();
    
15.11.2018 / 08:34