Let me first clarify the term clean. Cleanliness means referential transparency, i.e. You can replace the expression with the estimated result without changing the behavior of the program. Here is the action that returns the promise. To visualize the calculation, I am recording as a side effect:
const addAsync = (x, y) => new Promise((r, e) => { setTimeout( z => (console.log(z), r(z)), Math.random() * 1000, x + y ); }); console.log("before"); addAsync(2, 3); console.log("after");
Then I substitute the expression addAsync(2, 3) with my result, which is a Promise that contains 5 . Since there is no Promise literal in Javascript, I present an already established promise with Promise.resolve :
console.log("before"); Promise.resolve(console.log(5), 5); console.log("after");
Looking at the code there seems to be no difference. The addAsync(2, 3) expression gives an established promise (sort of like Promise(5) ). Promise.resolve(console.log(5), 5) , on the other hand, represents this very long promise. But, observing the side effects of console.log , we see that the evaluation order has changed, that is, the function that returns the promise actually changes the behavior of the program. Therefore, such a function is unclean.
source share