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.resolve
d.
- 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.resolve
d 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.