Photo by Christin Hume on Unsplash
Promises: Visualize the benefit of async
Reduce your code to a single line*
I'm taking several JavaScript courses, including a course by Jad Joubran.
The chapter I am on is teaching async/await
, and how they are syntactic sugar on top of a Promise
. Jad's course provides the learner with a sandboxed practice environment.
When pairing async
with an arrow function's implicit return
, three lines of code can be reduced to a single line, as seen below. Each of the below has the same outcome.
Full Promise
const canVote = age => {
return new Promise(resolve => {
resolve(age >= 18);
});
}
canVote(20).then(result => {
console.log(result); // true
});
async/await
const canVote = async age => {
return age >= 18
}
canVote(20).then(result => {
console.log(result); // true
});
Single line
const canVote = async age => age >= 18;
canVote(20).then(result => {
console.log(result); // true
});
Granted, this example an oversimplification of an async
function, though I can't imagine this doesn't have its uses.
There is of course also the bigger question of "code for the sake of brevity", versus "readable code". [The general consensus seems to be that "brevity === bad".]