Promise.all is not displaying the data

75 Views Asked by At

I am new to promises and I want to return the data from classes as promises. I have two classes with two function in each class. What I am doing each function is returning a promise from a class, but I am unable to execute promise.all. Below is the code

Class1

class TestClass {

    firstPromise() {
        return new Promise((resolve, reject) => {
            resolve('return first promise')
        })
    }

    secondPromise() {
        return new Promise((resolve, reject) => {
            resolve('return second promise')
        })
    }
}
module.exports.TestClass = TestClass;

Class2

class TestClass1 {

    firstPromise() {
        return new Promise((resolve, reject) => {
            resolve('return first promise')
        })
    }

    secondPromise() {
        return new Promise((resolve, reject) => {
            resolve('return second promise')
        })
    }
}
module.exports.TestClass1 = TestClass1;

Main function
    let data = req.body;
    let test1Object;
    let testObject;
    let testParam;
    let testParam1;
    if (data.hasOwnProperty('param1')) {
        test1Object = new test1.TestClass1();
        test1Object.firstPromise().then((data)=>{
            testParam1 = test1Object.secondPromise();
        });
    }
    if (data.hasOwnProperty('param2')) {
        testObject = new test.TestClass();
        testObject.firstPromise().then((data)=>{
            testParam = testObject.secondPromise()
        });
    }
    Promise.all([testParam,testParam1]).then((data)=>{
       console.log(data)
    });

it displays [ undefined, undefined ]

1

There are 1 best solutions below

0
On BEST ANSWER

When you're executing Promise.all(), the promises are not yet resolved, so testParam and testParam1 are undefined. I think you should assign the first promise to testParam1:

testParam1 = test1Object.firstPromise().then(data => test1Object.secondPromise());

and similarly the second to testParam:

testParam = testObject.firstPromise().then(data => testObject.secondPromise());