Hari Krishna
Hari Krishna

Reputation: 3538

Why and when to use Promise.resolve?

As I know, Promises are used to represent success/failure of an asynchronous operation. When I am looking into one of my project, all the functions are wrapping the final result in 'Promise.resolve'. I am not understanding, what is the use of wrapping all the function results in 'Promise.resolve'. Is there any use case here?

For example, all the functions are following below template.

process = (data) => {
  //Perform some operations.
  return Promise.resolve(result);
} 

Upvotes: 6

Views: 4078

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276296

The only reason to use Promise.resolve is converting a value that might be a promise to a promise.

Promise.resolve(value) is a convenience method that does new Promise(resolve => resolve(value). If the value is a promise it will be returned, if it is a promise from a userland promise library it will be converted to a native promise. If it is a plain value it will be converted for a promise fulfilled with that value.

Promise.resolve(5); // returns a promise fulfilled with the number 5.

This is useful in several cases, for example: - If a function might return a promise, it should always return a promise - so for example if you have a cached value it might need to be Promise.resolved. - If there are multiple implementations of functionality and some are synchronous - it creates a uniform interface.

Note that in practice with async functions this is not needed so much anymore since an async function always returns a promise - even if you return a plain value (in fact, whatever you return from an async function is Promise.resolved implicitly).

Also note that in particular you shouldn't make functions return promises if all they do is synchronous computation since a function returning a promise implies I/O in JavaScript.

Upvotes: 14

Related Questions