Machtyn Machtyn - 1 month ago 14
Javascript Question

Does a promise resolve in time to be part of a conditional

I need to test the result from a promise. Will a promise resolve in time to be part of a conditional?

if (myPromise() > 15 && myOtherPromise()) {
// do stuff when myPromise resolves to over 15 and myOtherPromise is true
} else {
// do stuff when myPromise resolves to 15 or less or myOtherPromise is false
}


Or do I just need to suck it up and do:

let myP = myPromise();
let myOtherP = myOtherPromise();

promise.all([myP, myOtherP]).then(function(res) {
if (res[0] > 15 && res[1]) {
// do stuff when myPromise resolves to over 15 and myOtherPromise is true
} else {
// do stuff when myPromise resolves to 15 or less or myOtherPromise is false
}
});


reposted from comment below for everyone "downvoting" the question and thinking this is a repeat.


Well, yes and no. No, because I'm working with Jasmine, where the expect calls automagically resolves a promise when one is passed.
expect(myPromise()).toBeGreaterThan(15)
. So from the outside, it might have been conceivable that an if's conditional might resolve a promise before performing any comparisons.

Answer

Assuming myPromise and myOtherPromise are functions that return promises which your code seems to indicate, then NO you can't do:

if (myPromise() > 15 && myOtherPromise()) {

Promises are objects. So if myPromise() returns a promise, then:

if (myPromise())`

is always truthy and that if statement has absolutely nothing to do with the eventual resolved value of the promise. So, that first if statement will NOT be checking the resolved value of either promise.


If you want to see the resolved value of a promoise, you HAVE to use something like .then() or .all() to get the resolved value. There is no other way to access the resolved value.

If you want to examine both the resolved values of myPromise() and myOtherPromise(), then you must wait for both of them to resolve and you should use Promise.all() as in your second code example:

Promise.all([myPromise(), myOtherPromise()]).then(function(results) {
    if (results[0] > 15 && results[1]) {
        // got the result we wanted
    }
}).catch(function(err) {
    // error here
});