0

I'm new to JavaScript and I'm struggling tying a couple of things together.

I need to set a global variable from within a function. The function is essentially querying a DB, getting an answer and doing a comparison to determine what variable to set.

Then, in a separate function, I need to set a value based on the value of the previous variable.

The problem I'm having is that the variables are only available within the function and I don't know how to set them to be available outside the function. I've tried to simplify the code so you can see what I'm attempting to do:

ddb.scan(scanparams, function(err, data) {
    if (err) {
        console.log(err);
    } else {
        var dbResp = data.key.value; //key is the name of the key, value is the value
        if (Number(dbResp) === Number(sessionId)) { //sessionId is defined elsewhere
            var result = '1';
        } else {
            var result = '0';
        }
    }
});

if result === '1' {
    doThing1;
} else {
    doThing2;
}

I can't move the logic for doThing into the previous function as it breaks other things. How can I expose the results of the DB query to other functions?

  • Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Klaycon Jun 25 '20 at 18:43
  • `How can I expose the results of the DB query to other functions?` The DB query is asynchronous, so any code that relies on its result is absolutely required to be asynchronous too. The code within the DB query happens in the future, and you can't pull the result from the future into the present. – Klaycon Jun 25 '20 at 18:45

0 Answers0