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?
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.
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.
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.
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.
simple:
var promiseResolve, promiseReject; var promise = new Promise(function(resolve, reject){ promiseResolve = resolve; promiseReject = reject; }); promiseResolve();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With