JavaScript Promises

Leave a comment

JavaScript promises are a way in JavaScript to write asynchronous code in a synchronous way. They are asynchronous callbacks, but in terms of error handling are much more readable. Here we will go through an example of how to use promises.

We define a promise as below, with 2 parameters, resolve and reject:

new Promise((resolve, reject)

If the promise is resolved, we can perform an action, and if it is rejected, we can perform a different action.

A promise has 3 states:

  1. Pending
  2. Resolved
  3. Rejected

Promises use “then” for chaining. This means you can run several asynchronous operations that rely on the completion of each other.

For example, let’s say we want to call a promise that takes 5 seconds to run something. If successful, let’s call resolve:

(new Promise(function(resolve, reject) {
    // This will be resolved successfully in 5 seconds
    setTimeout(function() {
        console.log("Resolved");
        resolve();
    }, 5000);
    setTimeout(function() {
        console.log("This is taking too long. Let's reject");
        reject();
    }, 10000);
})).then(function () {
    console.log("Resolved. We can now do more things");
}, function () {
    console.log("Promise failed");
});

This outputs below, where the Resolved timeout runs after 5 seconds, and then prints the resolved “then” function. Then after 5 more seconds, the second timeout runs:

With this pattern, you can make asynchronous calls, and decide if they failed or not due to their results, then based on that, decide what to do next.

For example, let’s say in our example, we will wait 5 seconds to define success, but “then” our next function will be rejected:

let p = new Promise(function(resolve, reject) {
    // This will be resolved successfully in 5 seconds
    setTimeout(function() {
        console.log("Resolved");
        resolve();
    }, 5000);
})

p.then(function () {
    console.log("We can now do more things");
    // But what if this new code failed
    reject();
}, function () {
    console.log("Promise failed");
    reject();
}).then(function () {
    console.log("Success!");
}, function () {
    console.log("Failed!");
});

This produces:

At each point in the process, asynchronous calls will be handled in the way defined.

 

THANKS FOR READING. BEFORE YOU LEAVE, I NEED YOUR HELP.
 

I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.

IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.

THANK YOU, AND LET'S KEEP LEARNING TOGETHER.

CARL

https://www.youtube.com/carldesouza

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

Leave a Reply

Your email address will not be published. Required fields are marked *