Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Javascript Promise - execute after .then() is called

If you want to execute code after a callback is called in JavaScript, then you can just place it after the callback:

function demoCallback(callback) {
  callback()
  console.log("I execute second")
}

demoCallback(() => {
  console.log("I execute first")
})

Is it possible to do the same thing with an ES6 Promise from within the scope of the function? Let's say I have a function that returns a Promise:

function demoPromise() {
  return new Promise((resolve, reject) => {
    resolve()
    console.log("I execute first")
  })
}

demoPromise().then(() => { console.log("I execute second") })

The Code inserted after resolve executes once the Promise is resolved, but before then is called outside the scope of the function. Is there a way that I can execute code after both, but do so from within the scope of the function?

like image 560
Max K Avatar asked Jul 23 '18 14:07

Max K


People also ask

What is Promise resolve () then?

The Promise. resolve() method "resolves" a given value to a Promise . If the value is a promise, that promise is returned; if the value is a thenable, Promise. resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.

What is then () in JavaScript?

then() The then() method returns a Promise . It takes up to two arguments: callback functions for the fulfilled and rejected cases of the Promise .

How Promise is executed in JavaScript?

Just to review, a promise can be created with the constructor syntax, like this: let promise = new Promise(function(resolve, reject) { // Code to execute }); The constructor function takes a function as an argument. This function is called the executor function .

Does Promise execute After resolve?

resolve() is not a JS control statement that magically would have the effect of return , it's just a function call, and yes, execution continues after it.


2 Answers

Is it possible to do the same thing with an ES6 Promise from within the scope of the function?

No, this isn't possible. then callbacks always run asynchronously, and that includes being asynchronous in regard to the resolve() call.

(That said, promise callbacks are queued, so you can abuse that queue to get your code behind the other:

function demoPromise() {
  const p = new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
      p.then(() => {
        console.log("I execute second");
      }); // because I will be scheduled second
    }, 1000);
  });
  return p;
}

demoPromise().then(() => {
   console.log("I execute first");
}); // because I was scheduled first

But please don't do that)

If you want to execute code after a callback is called in JavaScript

then you probably should not just return a promise. Take a callback that does what you want before executing your code:

function demoPromise(callback) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, 1000);
  }).then(() => {
    return callback();
  }).then(res => {
    console.log("I execute second");
  });
}

demoPromise(() => {
   console.log("I execute first");
}).then(() => {
   console.log("I execute last");
});

This is known as the disposer pattern and very useful for handling resources.

like image 61
Bergi Avatar answered Sep 18 '22 04:09

Bergi


You can resolve the Promise with a function that can be called in a then block. So long as that function is called within the block, you can execute code before it like so

function demoPromise() {
  return new Promise((resolve, reject) => {
    resolve(function(){
        console.log("I execute second")
    });
  })
}

demoPromise().then(f => { console.log("I execute first");f();})
like image 45
Hikmat G. Avatar answered Sep 18 '22 04:09

Hikmat G.