Member-only story
From fetching data to handling user input, orchestrating all the many asynchronous flows within modern web applications has long been a trying affair.
Traditionally done through cascading callback functions, coordinating even seemingly simple sequences can quickly devolve into pyramid code nobody dares thereafter touch.
However, a simpler approach to managing concurrency called Promises now exists natively within JavaScript. Promises provide a cleaner paradigm around composing chains of asynchronous operations.
In essence, Promises wrap async functions, standardizing responses via resolved or rejected states rather than raw return values. This abstraction helps avoid race conditions and inversion challenges around coordinating waterfalls of callbacks.
Converting callback APIs to Promises is straightforward:
/* Callback */
function getUser(id, callback){
// Async lookup
if(success) callback(user);
else callback(error);
}
/* Promise Wrapper */
function getPromiseUser(id){
return new Promise((resolve, reject) => {
getUser(id, (user) => {
resolve(user);
})
});
}