The first "a" in "AJAX" stands for
asynchronous. That means the function returns
before the request has completed.
You cannot use the values returned from the AJAX request until that request has completed.
You'll need to return
a Promise[
^], which will return the array value once the request has completed.
function function1() {
return $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
url: "/Bus/AjaxMethod",
dataType: "json",
}).then(function(data){
debugger;
return data.split(',');
}).fail(function(data){
console.log("Error ", data);
alert("Error");
});
}
You will then need to delay the code which uses the return value until the method returns. You can either use a continuation:
function1().then(function(s) {
debugger;
console.log("Returned array", s);
});
or
use async
and await
[
^]:
async function doIt(){
const s = await function1();
debugger;
console.log("Returned array", s);
}
doIt();