Execution order on a Promise

Asked

Viewed 47 times

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 notice the execution of this code generates as output:

// Iniciou
// Finalizou
// Executando

I honestly have no idea why this should occur, if anyone can clear up this doubt.

1 answer

2


In a file when you return the result 'resolve' what you are doing and send the result to the 'then' being asynchronous this action and running the functionality later to resolve immediately.

The right thing to do solves the last:

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

  • 1

    Thank you for the reply.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.