5

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);
} 
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
Hari Krishna
  • 3,658
  • 1
  • 36
  • 57
  • what if you have a strategy pattern that expects a promise for a result, but you have a synchronous function? – Daniel A. White Feb 16 '19 at 14:02
  • [Don't return promises from otherwise synchronous functions!](https://stackoverflow.com/q/45683984/1048572) – Bergi Feb 16 '19 at 14:34

1 Answers1

9

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.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • 1
    Your first sentence is really not right. That's not the ONLY reason to use `Promise.resolve()` as even your own cache example explains. Sometimes you already have the value (which you know is NOT a promise), but need to return a promise that resolves to that value. You could pick better wording for that first sentence. – jfriend00 Feb 16 '19 at 17:09