How To Execute Promises In Sequence

How To Execute JavaScript Promises In Sequence

In this tutorial, you’ll learn how to execute JavaScript promises in sequence. If you are unfamiliar with JavaScript promises, I would recommend getting a basic understanding of how JavaScript promises work.

Creating a JavaScript Promise

Let’s start by creating a JavaScript promise. I’ll define a function which will return a promise which gets resolved after a specific time interval.

function createPromise(i) {
    let timeperiod = 1000;
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(i)
        }, timeperiod)
    })
}

As seen in the above code, I have used setTimeout to delay the response from the promise. Delay may be assumed as the network delay while trying to make API calls.

I have an array with two numbers. I’ll be iterating the array and try to create a promise for each item.

[1,2].forEach(function(i){
    createPromise(i)
    .then(function(response){
        console.log('response is ',response)
    })
})

Save the above changes and try running the code. If you check the browser console, you’ll have the results logged in sequence.

response is  1
response is  2

Now lets say due to some network issues the result from the first promise is resolved only after the second promise is resolved. To simulate the situation I’ll modify the createPromise method.

function createPromise(i) {
    let timeperiod = 1000;
    if(i == 1) {
        timeperiod = 5000;
    }
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(i)
        }, timeperiod)
    })
}

As seen in the above code, if the item is 1 the promise resolution is delayed by 5 seconds. Save the changes and reload the HTML page with JavaScript.

response is 2
response is 1

Now in such a case it’s difficult to maintain promise resolution in sequence.

JavaScript Promises In Sequence

JavaScript provides a method to solve the above problem. Promise.all method returns a single promise when the array of promises passed to it gets resolved or any one of promises gets rejected. And it helps in maintaining the promise sequence.

In order to use Promise.all, create an array to keep both of promises created using the createPromise method.

let promises = [];
[1,2].forEach(function(i){
    promises.push(createPromise(i))
})

Use Promise.all which will return a promise which gets resolved when all promises have been resolved.

Promise.all(promises)
.then((result) => {
    result.forEach((response) => {
        console.log('result is ', response)
    })
})

Save the above changes and refresh the web page. The response from Promise.all maintains the same order in which the promises were pushed into the promises array.

result is 1
result is 2

Here is the complete HTML file with JavaScript code :

<!DOCTYPE html>
<html>
<head>
    <title>How To Execute JavaScript Promise In Sequence</title>
    <script type="text/javascript">
    function createPromise(i) {
        let timeperiod = 1000;
        if(i == 1) {
            timeperiod = 5000;
        }
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve(i)
            }, timeperiod)
        })
    }

    let promises = [];
    [1,2].forEach(function(i){
        promises.push(createPromise(i))
    })

    Promise.all(promises)
    .then((result) => {
        result.forEach((response) => {
            console.log('result is ', response)
        })
    })
    </script>
</head>
<body>

</body>
</html>

Wrapping It Up

In this tutorial, you learnt how to execute JavaScript promises in sequence using Promise.all method. Promise.all method maintains the same order for the promise result as the promise array passed into the Promise.all method.