Dotnet Expert Dotnet Expert - 2 months ago 8
Node.js Question

How to return promise from a function that itself uses promise?

What I am trying to do is basically

function test() {
getSomeValue().then(function (data) {
//process data
});
}

function getSomeValue() {
//do some long process
return new Promise(function (resolve, reject) {
resolve(result);
});
}

function getSomeOtherValue() {
//do some long process
return new Promise(function (resolve, reject) {
resolve(result);
});
}


Function test calls a function that returns a promise and then performs some calculations on the data returned. This part works fine. Now the function
getSomeValue
needs to call another function which also returns a promise. How do I return a promise from
getSomeValue
which also waits for
getSomeOtherValue
to completed.

Let me know if any other information needed.

Answer

You can just chain getSomeOtherValue inside getSomeValue:

function getSomeValue() {
    //do some long process 
    return new Promise(function (resolve, reject) {
        resolve(result);
    }).then(getSomeOtherValue);
}

If you want the order to be switched then:

function getSomeValue() {
    //do some long process 
    return getSomeOtherValue().then(function () {
        return new Promise(function (resolve, reject) {
            resolve(result);
        });        
    }
}

However, this is for illustration only. You can design your promises so that you can chain them effectively on a higher level:

function test() {
    getSomeOtherValue()
        .then(getSomeValue)
        .then(function (data) {
            //process data
        });
}