Both examples are pointless because code is synchronous.
If you have a traditional callback function such as setTimeout
you have to use new Promise
to convert it to a promise (you cannot return Promise.resolve(value)
from a callback:
const later = (howLong, value) =>
new Promise(
resolve =>
setTimeout(() => {
console.log(value);
resolve(value)
}, howLong)
);
Using Promise.resolve
can be used as an initial value for example when you reduce values asynchronously:
[1,2,3].reduce(
(all, item) =>
all.then(
() => later(2000, item)
),
Promise.resolve()//initial value of all
)
Another common use case is if your function has to return a promise but can return a value immediately. Let's say you fetch some data and cache it when you got it. The next time you call the function you want it to return a promise because the caller is expecting a promise. You wrap the cached value in a promise:
const getData = (
cache => () =>
(cache)
? Promise.resolve(cache)
: fetch("someURL").then(r=>r.json()).then(result=>{
cache=result;
return result;
})
)(false)