1

I'm very new to this, so I really hope someone can help me.

My struggle is with some "undefined" variables, and I believe it is due to asynchronous functions.

A simplified version of my code:

document.getElementById("applyButton").addEventListener("click", () => {

    // Variables from input form
    var nameInput = document.getElementById("nameID").value;
    var typeInput = document.getElementById("typeID").value;

    // Database lookups
    var thisNameID = getNameID(nameInput);
    var thisTypeID = getTypeID(typeInput);  

    // Some code with the variables
    var newQuery = "INSERT INTO myTable (myNameID, myTypeID) VALUES ('" + thisNameID + "', '" + thisTypeID + "');";    
    console.log("Query: ", newQuery);

});

function getNameID (input){
    // do some database lookup
    return returnedNameID;
};

function getTypeID (input){
    // do some database lookup
    return returnedTypeID;
};

In the console I get:

Query: INSERT INTO myTable (myNameID, myTypeID) VALUES ('undefined', 'undefined');

How do I make sure that I wait for the function to reply? I've been looking into Promises and Callbacks, and other similar questions here, but must admit I'm confused, and can't wrap my head around how to implement it in my code above.

Please if anyone could show me an implementation with promises or a similar solution.

Many thanks in advance!

Runberg
  • 19
  • 2
  • 3
    Looks like `getNameID` and `getTypeID` don't return anything, not even promises, else they wouldn't be `undefined`. – CertainPerformance Apr 04 '18 at 06:24
  • Just try to put a console log into getNameID or getTypeID. If the return val is undefined, the problem would be in database lookup logic. – Yogesh Patil Apr 04 '18 at 06:29
  • I actually did this in my real code, and inside the functions I do get a value when sending to console .. BUT this value is written in the console AFTER the console.log("Query: ", newQuery); This is why I assume it's an issue with asynchronous functions - and even I have tried to read about it, I simply can't wrap my head around how to implement it :( – Runberg Apr 04 '18 at 07:11

0 Answers0