Asynchronous code: Promises

barriosdfreddy

Barrios Freddy

Posted on December 2, 2020

Asynchronous code: Promises

A promise is an object representing the eventual completion or failure of an asynchronous operation.

Basically, a promise is an object where you can attach a numberless callback function which can be pass as arguments to the chainable methods then, catch and finally.

The Promise constructor receives the executor function which waits for two functions, in the first position the resolve function which will be executed if everything is done, and in the second position the reject function that will be executed in case of an error, for example.

new Promise(function(resolve, reject) {
    const name = "Freddy"
    resolve(name)
}).then(name => {
    console.log("It's a pleasure, Mr. " + name);
    throw new Error("Something wrong happened!")
    console.log("This will not be displayed");
}).catch(error => {
    console.error("What happened? " + error.message)
}).finally(() => {
    console.log("There is no coffee to drink");
})

// It's a pleasure, Mr. Freddy
// What happened? Something wrong happened!
// There is no coffee to drink

Enter fullscreen mode Exit fullscreen mode

Definitely, Promises give our code more readability, consistency and come to resolve some problems suffered from the callback functions such as the famous "Callback hell". Thus, if you are not using promises in your normal day, this is the moment.

💖 💪 🙅 🚩
barriosdfreddy
Barrios Freddy

Posted on December 2, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related