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!