I have a jQuery ajax call that I want to do some task in order after the result comes.
$.ajax({
url : 'https://api.spacexdata.com/v3/launches',
type : 'GET',
dataType:'json',
success : function(data) {
data.forEach(async function(element) {
await console.log(element.flight_number);
await auto(element.flight_number);
});
},
error : function(request,error) {
console.log(request,error);
}
});
function auto(val) {
$.ajax({
url : 'https://api.spacexdata.com/v3/launches/latest',
type : 'GET',
dataType:'json',
success : async function(data) {
await console.log('second api called' , data);
},
error : function(request,error) {
console.log(request,error);
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
the out put is :
1
2
3
4
...
second api called Obj
second api called Obj
second api called Obj
second api called Obj
...
but the expected result is :
1
the second api called
2
the second api called
3
the second api called
4
the second api called
....
here is the jsfiddle:
Do you have any idea what is wrong with the loop? I want the sequence I mentioned!
awaitcommand relinquishes control to the next operation (in your case the next iteration of the loop) until the command being awaited completes. As these are AJAX requests they will take much longer than the 5-10 ms than aforloop does.valargument is never usedthisinside the result handler, this way you can safely link requests to the responses. this doesn't exactly solve your issue, but what you ask for would really require synchronous processing, which isn't great. see here for more details: stackoverflow.com/questions/5097191/ajax-context-optionautofunction be async and return a Promise object so it can really be awaited?