1

I am trying to understand JS better. I have defined a variable test, where I attempted to update it inside the function in order for it to take the value of the list of an object contained in a variable, mySum. Despite this printing to the console correctly, mySum prints undefined when tested in the final line to see if it's updated. Can I get some guidance on what I'm doing incorrectly with respect to updating the global variable, test?

var test;
    knex("my_table").sum("funds").where("user_id",2)
    .then(function (mySum){
        return mySum;
    })
    .then(function (mySum){
        knex("my_table").select("funds").where("funds",mySum[0]['sum'])
        .bind(console)
        .then(console.log)
        test = mySum;
    });
console.log(test);

Edit: I understand it now. To use this within the EJS something like this would need to be constructed to get two variables representing funds for two different users in this case...

app.get("/", function(req,res){
    knex("my_table").sum("funds").where("user_id",2)
    .then(function(mySum){
        knex("my_table").sum("funds").where("user_id",3)
        .then(function(mySum2){
        res.render("home", {
        page_title: 'home',
        mySum: mySum[0]['sum'],
        mySum2: mySum2[0]['sum']
        });
        })

    });

1 Answers1

0

As others have commented, console.log(test) fires prior to test = mySum because your code is asynchronous. The .then is a promise that fires when the prior code completes but the rest of the code will continue to process in the meantime. Here is some documentation regarding promises in JavaScript.

  • After reading through the document, I attempted the following `function sums(){ var val = await knex("my_table").sum("funds").where("user_id",2) .then(function(value){ return value; }); return val; }; var test2 = sums(); console.log(test2," test2");` but am getting `var test2 = async function sums(){ ^^^^^^^^ SyntaxError: Unexpected token function ` – a programmer May 13 '17 at 16:08