Reputation: 186
Consider these two functions:
function a(){
//...
if(something) {
return Promise.resolve();
} else {
return Promise.reject();
}
}
function b(){
//...
return new Promise((resolve, reject) => {
if(something) {
resolve();
} else {
reject();
}
});
}
I met more often with second approach, but first one looks a bit cleaner for me. Are there any specific, rare use cases when code would work different with each approach, or is it just semantics?
Upvotes: 4
Views: 107
Reputation: 39250
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)
Upvotes: 3
Reputation: 134
The only difference that I can see is that function b() returns the **whole promise and can take the accept and reject function from the **parameters of b function. Whereas, the function a() is a predefined Promise, which could have been passed into a() but all the same it's accept and reject are set in stone and returns those functions instead of the Promise Object.
Upvotes: 0