Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolve Javascript Promise outside function scope

I have been using ES6 Promise.

Ordinarily, a Promise is constructed and used like this

new Promise(function(resolve, reject){     if (someCondition){         resolve();     } else {         reject();     }  }); 

But I have been doing something like below to take the resolve outside for the sake of flexibility.

var outsideResolve; var outsideReject; new Promise(function(resolve, reject) {      outsideResolve = resolve;      outsideReject = reject;  }); 

And later

onClick = function(){     outsideResolve(); } 

This works fine, but is there an easier way to do this? If not, is this a good practice?

like image 840
Morio Avatar asked Oct 01 '14 20:10

Morio


People also ask

What does resolve () do in a 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.

How do you force promise to resolve?

You can use the async/await syntax or call the . then() method on a promise to wait for it to resolve. Inside of functions marked with the async keyword, you can use await to wait for the promises to resolve before continuing to the next line of the function.

Does resolve return a promise?

resolve() method in JS returns a Promise object that is resolved with a given value. Any of the three things can happened: If the value is a promise then promise is returned. If the value has a “then” attached to the promise, then the returned promise will follow that “then” to till the final state.

What happens if you don't resolve a promise Javascript?

A promise is just an object with properties in Javascript. There's no magic to it. So failing to resolve or reject a promise just fails to ever change the state from "pending" to anything else. This doesn't cause any fundamental problem in Javascript because a promise is just a regular Javascript object.


1 Answers

simple:

var promiseResolve, promiseReject;  var promise = new Promise(function(resolve, reject){   promiseResolve = resolve;   promiseReject = reject; });  promiseResolve(); 
like image 99
carter Avatar answered Sep 19 '22 08:09

carter