I’m currently using 3 ajax call methods (3 of them are executing back-to-back). I must have a time delay in between the second ajax call and the third one. If I add “async:false” in the second ajax, everything works like a charm. However, I found out that this is really a terrible practice and shouldn’t be using. So I decided to try an async/await. This is my first time, so have no luck. I would be really grateful if you guys could add some explanations so I can learn. Thank you so much.
JavaScript
x
20
20
1
//This is the second ajax method that I've been trying to use async/await
2
async function InsertAssignments(data) {
3
var insertNewData = api + "/Point/insert_data/";
4
await $.ajax({
5
type: "POST",
6
url: insertNewData + data,
7
dataType: "json",
8
data: data,
9
timeout: 30000,
10
success: function (data) {
11
$("#mainGrid").data("kendoGrid").dataSource.read();
12
$("#ListBox1").data("kendoListBox").dataSource.read();
13
$("#ListBox2").data("kendoListBox").dataSource.read();
14
},
15
error: function (xhr, status, error) {
16
$('#gridMessage').html(xhr.responseText).css("color", "red");
17
}
18
});
19
}
20
and then I’m calling InsertAssignments(data) somewhere.
Advertisement
Answer
Async
/await
requires functions to return a promise.- jQuery
$.ajax()
can be used in two ways: with callbacks and promises. Your code is using a callback, not a promise.
Wrap $.ajax()
in a function like this:
JavaScript
1
9
1
async function doAjax(url, params = {}, method = 'POST') {
2
return $.ajax({
3
url: url,
4
type: method,
5
dataType: 'json',
6
data: params
7
});
8
}
9
Then use await doAjax()
whenever you are making an ajax call.
JavaScript
1
12
12
1
async function InsertAssignments(data) {
2
const insertNewData = api + '/Point/insert_data/';
3
try {
4
// You can make multiple ajax calls
5
// Response data is stored in result
6
const result = await doAjax(insertNewData, data);
7
} catch (error) {
8
console.log('Error! InsertAssignments:', error);
9
$('#gridMessage').html(error.message).css('color', 'red');
10
}
11
}
12