getUsers();
function getUsers(){
console.log('Start');
$.ajax({
url: 'https://jsonplaceholder.typicode.com/users',
method: 'GET',
dataType: 'json',
success: function (data) {
data.forEach(user => {
console.log(user.id);
});
},
error: function () {
console.log(data.status);
}
})
console.log('End');
}
The above code-example should print the following: Start ids ... End
However it has the following problem: The order of printing of the data is wrong. It prints Start End data-object
I know it has to do with async, however I can't fix the problem. I tryed alot of things like $.When() Promise async/await But none of them helped.
So could you please show how to fix this problem?
Thank you in advance
Ajax is asynchronous, the successor the error function will be called later, when the server answer the client. That is why sometimes you can see data.status displayed before End in your last console.log statement. Second, data that you are getting from response does not contain field success. Success callback function gets passed three arguments: The data returned from the server, formatted according to the dataTypeparameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHTobject. In your code you are just passing first argument to it which is data returned from server.