Austin Gayler
Austin Gayler

Reputation: 4356

How to conditionally wait for a promise to resolve?

I call a function,

getResponse(Math.random());
doSomethingWith(someVar);


getResponse(num) {
  if(num > 0.8) someVar = "whee";
  if(num > 0.5) someVar = "whoo";
  if(num > 0) callSomeOtherFunctionWhichDoesABunchOfDatabaseQueriesThatUsePromisesAndEventuallySetssomeVar();
}

Is there a way that I can wait for callSomeOtherFunctionWhichDoesABunchOfDatabaseQueriesThatUsePromisesAndEventuallySetssomeVar() to finish and set someVar ? I was thinking I could also wrap the assignments of someVar in a promise, to then make getResponse then()able, but that seems a bit excessive since I only have one case that I have a bunch of asynchronous work being done to determine someVar.

Upvotes: 1

Views: 593

Answers (1)

Jaromanda X
Jaromanda X

Reputation: 1

Note, replaced callSomeOtherFunctionWhichDoesABunchOfDatabaseQueriesThatUsePromisesAndEventuallySetssomeVar with someFunc in code below :p

getResponse needs to return a promise, always

so

function getResponse(num) {
    return Promise.resolve()
    .then(() => {
        if (num > 0.8) {
            someVar = "whee";
            return;
        }
        if (num > 0.5) {
            someVar = "whoo";
            return;
        }
        if (num > 0) {
            return someFunc();
        }
    });
}

Please note - the logic in your original code would (almost) always run that long winded function, because Math.random() is almost always > 0

the rest of the code would simply be

getResponse(Math.random())
.then(() => doSomethingWith(someVar));

if someFunc resolves to the value it sets someVar to, you could make the code a little nicer

var getResponse = num => Promise.resolve()
.then(() => {
    if (num > 0.8) {
        return "whee";
    }
    if (num > 0.5) {
        return "whoo";
    }
    return someFunc();
});

getResponse(Math.random())
.then(someValue => doSomethingWith(someValue));

but that may not be useful if someVar is used in other ways

Upvotes: 4

Related Questions