A promise that is just coming back?

I noticed the following in the code base I'm working with right now, and I'm not sure what this item is:

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

Is there a reason to have an empty promise? This reminds me of setTimeOut(fn, 0) , and I wonder if it has a similar effect.

thanks

+5
source share
2 answers

Edit

As B. Bergi noted, this promise is never fulfilled, since no one names the solution. Thus, this promise will never cause anyone to expect a result.

Both equivalent to setTimeOut(fn, 0) would be:

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

Original

Yes, the effect is similar. The Promise specification indicates that even if Promise is in an executed state, any handler will not be called immediately when the handler is registered. It will only be called when the current call is being made.

 spinnerPromise.then (()=> { /* Code called later */ }); // Code called after call to then 
+4
source

Is there a reason to have an empty promise?

I can’t think of many. One use case is a value that you can pass to Promise.race and expect it to always take another option.

Look Are JavaScript forever awaiting promises bad? and is it safe not to allow or reject the promise .

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

No, absolutely not. setTimeout will eventually call the callback, but new Promise(() => {}).then(…) never will. This is more like moving from Infinity to setTimeout (which really doesn't really work ).

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

+3
source

Source: https://habr.com/ru/post/1273721/


All Articles