Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise that just returns?

I noticed the following in the code base I'm currently working with and am not sure what the point of it is:

public spinnerPromise: Promise<void> = new Promise<void>(() => { return; });

Is there a reason to have an empty Promise? This reminds me of doing a setTimeOut(fn, 0) and I'm wondering if it has a similar effect.

Thanks

like image 301
User 5842 Avatar asked Nov 28 '17 14:11

User 5842


2 Answers

Edit

As @Bergi pointed out, the given promise never fulfills as no one calls resolve. So the promise in question will never call anybody waiting for the result.

A promise equivalent to a setTimeOut(fn, 0) would be:

var spinnerPromise: Promise<void> = new Promise<void>(resolve => resolve());

Original

Yes the effect is similar. The Promise specification mandates that even if the Promise is in the fulfilled state, any handler will not be called right when the handler is registered. It will get called only when the current call is done executing.

spinnerPromise.then (()=> { /* Code called later */ });
// Code called after call to then 
like image 162
Titian Cernicova-Dragomir Avatar answered Dec 08 '22 17:12

Titian Cernicova-Dragomir


Is there a reason to have an empty Promise?

I can't think of many. One use case would be as a value that you can pass to Promise.race and expect it to always take the other choice.

Have a look at Are JavaScript forever-pending promises bad? and Is it safe to not resolve or reject a promise.

This reminds me of doing a setTimeOut(fn, 0) and I'm wondering if it has a similar effect.

No, not at all. setTimeout will eventually call the callback, but new Promise(() => {}).then(…) never will. It's more akin to passing Infinity to setTimeout (which doesn't really work in reality).

You might be thinking of Promise.resolve().then(…) or new Promise(r => r()).then(…), which will call the callback function immediately but asynchronously.

like image 36
Bergi Avatar answered Dec 08 '22 17:12

Bergi