I’ve recently started learning javascript and I’m having a big problem understanding the async behavior of the language. I’ve spent hundreds of hours searching and everyone recommends the use of promises but I can’t quite comprehend what I’m doing wrong (maybe all of it lol).
I tried with promises as recommended by almost everyone in every forum and came up with this code but somehow I can’t manage to make it wait for function1 to be finished in function2, since I get that promise1 is undefined.
` async function function1() {
let query = “SELECT * FROM table1”;
connection.query(query, (error, result) => {
if (error) throw error;
console.log("Length " result.rows.length);
let result_query = [];
let i = 0;
while (i < result.rows.length) {
result_query.push(result.rows[i]);
i++;
}
let customPromise = new Promise((resolve, reject) => {
if(result_query.length > 0){
resolve(result_query);
} else {
reject(new Error('ERROR'))
}
});
customPromise.then(() => {
return customPromise;
});
};
async function function2() {
promise1 = await function1();
promise1.then(function(){ //HERE I GET THAT PROMISE1 IS UNDEFINED
console.log("Exit");
})
}`
This is my original code where I realized javascript has an asynchronous nature and it prints “Exit” in function2 before function1 is finished. I’m sorry if this is an obvious question but I feel stuck. Thank you all for your kindness in helping strangers.
` async function function1() {
let query = “SELECT * FROM table1”;
connection.query(query, (error, result) => {
if (error) throw error;
console.log("Length " result.rows.length); //*THIS PRINTS AFTER THE EXIT IN FUNCTION2
let result_query = [];
let i = 0;
while (i < result.rows.length) {
result_query.push(result.rows[i]);
i++;
}
if(result_query.length > 0){
return(result_query);
} else {
return("ERROR");
}
};
async function function2() {
function1();
console.log("Exit"); //*THIS PRINTS BEFORE EVERYTHING
}
OUTPUT:
Exit
Length 2`
Sebastián is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.