Sorry if this is extremely simple, I can’t get my head around it. I’ve seen similar questions but nothing which gets to the heart of my problem, I think. I have a simple async function:
async function isOpen() {
var open;
var data = $.ajax({
//Working code here
});
data.done(function(dat) {
var obj = JSON.parse(dat);
var msg = "";
for (var i = 0; i < obj.length; i++) {
let closingDate = Date.parse(obj[i].close);
let openingDate = Date.parse(obj[i].open);
if (closingDate > Date.now() && openingDate < Date.now()) {
open = true;
} else {
open = false;
}
}
});
return open;
}
I know that this code is all working – using console.log I have seen that open is always successfully assigned to true or false. So I call this async function from another async function:
async function testFunction(){
const open1 = await isOpen();
//More code here...
}
But open1
(in testFunction
) is always undefined – even though I use await
.
Any ideas what this could be?
2
Answers
of course, the value of
open
will be determined by the lastobj[i]
So you want
Or even
This is happening because you are using a callback for ajax request and not waiting for ajax request to complete, which is going to set
open
inisOpen
. You can return a Promise to resolve this,Note: For the above code, you need to handle the logic for errors in the callback, using
reject
otherwise it will hang forever.