Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I resolve a Promise from the outside?

Using ES2015, can I resolve a promise from the outside i.e. trigger a resolution after its creation?

Like

const promise = new Promise();
promise.then(() => foo());
promise.resolve(); // foo() gets executed
like image 670
Lukas Avatar asked Jun 24 '16 09:06

Lukas


People also ask

How do you resolve an existing Promise?

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.

How do you handle rejection promises?

We must always add a catch() , otherwise promises will silently fail. In this case, if thePromise is rejected, the execution jumps directly to the catch() method. You can add the catch() method in the middle of two then() methods, but you will not be able to break the chain when something bad happens.

Can you catch a Promise rejection?

If an error condition arises inside a promise, you “reject” the promise by calling the reject() function with an error. To handle a promise rejection, you pass a callback to the catch() function. This is a simple example, so catching the rejection is trivial.

Can a Promise be Cancelled?

Promises have settled (hah) and it appears like it will never be possible to cancel a (pending) promise. Instead, there is a cross-platform (Node, Browsers etc) cancellation primitive as part of WHATWG (a standards body that also builds HTML) called AbortController .


1 Answers

Yes you can.

let resolvePromise = null;
const promise = new Promise(resolve => resolvePromise = resolve);
promise.then(foo => console.log(foo));
resolvePromise('bar');
like image 94
Yury Tarabanko Avatar answered Sep 23 '22 23:09

Yury Tarabanko