Search code examples
javascriptes6-promise

How to implement Javascript promises for 3 functions?


I have 3 functions that both take their specific time to execute, then when they are all finished I need to trigger a certain function. With the following code, I am able to get the expected results with a single function but with multiple function I am failing to do it, please help me edit this code to wait for my 3 functions then console the data they returned.

var promise = new Promise(function(resolve, reject) 
{
    setTimeout(function() 
    {
        resolve('hello world');
    }, 2000);
});

promise.then(function(data) 
{
    console.log(data);
});

Solution

  • Promise.all() will take an array of promises as a parameter and wait for all promises to complete.

        var promise1 = new Promise(function (resolve, reject) {
        setTimeout(function () {
            resolve('function 1 resolved');
        }, Math.random() * 10000);
    });
    
    var promise2 = new Promise(function (resolve, reject) {
        setTimeout(function () {
            resolve('function 2 resolved');
        }, Math.random() * 10000);
    });
    
    var promise3 = new Promise(function (resolve, reject) {
        setTimeout(function () {
            resolve('function 3 resolved');
        }, Math.random() * 10000);
    });
    
    Promise.all([promise1, promise2, promise3])
        .then(resArr => {
            console.log(resArr)
        })
    

    You can catch the error occurred in any of promise by using .catch() attached to promise.all()

    Promise.all([promise1, promise2, promise3])
        .then(resArr => {
            console.log(resArr)
        })
        .catch(error => console.log(error))