2Minutes: Promises In JavaScript
In JavaScript, when we want to perform asynchronous operations, we use Promises. They also help us avoid “Callback Hell,” a situation where nested callbacks make code difficult to read, understand, and maintain. Search for “Callback Hell” to see how quickly code can become hard to follow.
// Before Promises
function func1(success, failure) {
const state = true;
if (state)
success("You win!");
else
failure("You lose!");
}
func1(
res => {
console.log(res);
},
err => {
console.log(err);
}
);
// With Promises
const promise = new Promise((resolve, reject) => {
const state = true;
if (state)
resolve("You win!");
else
reject("You lose!");
});
promise
.then(res => {
console.log("Success ", res);
})
.catch(err => {
console.log("Error ", err);
});Definitely the second one looks cleaner, readable, and more maintainable.
A Promise always returns a Promise object. There are two main ways to handle its result: either with .then() and .catch(), which we covered in the previous example, or with async/await, which we’ll explore in upcoming posts, in shāʾ Allāh.
That’s 2Minutes, see you in the next one !
Sources
MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
GeeksForGeeks: https://www.geeksforgeeks.org/javascript/javascript-promise/