The awesome Javascript combination, Promise, async / await
Javascript Promise is definitely a great addition to the language’s features. It has added a nice and clean way to handle asynchronous processes and their results between resolved and rejected.
But as experience may show us, sometimes, this organized way of then()/catch() for successful or failed returns may be confusing and ends up with unexpected results.
Is it something wrong with this new great feature called Promise? or is it just the way it behaves? and what can we do to fully optimize the result and get what we really want? Let’s take a look.
Let’s look at this example below.
const returnString = ((s, n) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Resolving Promise ', n)
resolve(s);
}, 300);
});
});
This is a simple function which takes a string (s) and a number (n), simulate a processing time of 300 milliseconds, and then displays a message on console and returns the passed string.
This function represents an asynchronous process such as interacting with database to read or write data, or handling files.
According to MDN Web Docs, the term asynchronous refers to two or more objects or events not existing or…