Saturday, 1 October 2016

javascript - Difference between Promise returns



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?


Answer



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)

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...