Skip to content
Advertisement

Jquery async/await ajax call

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.

//This is the second ajax method that I've been trying to use async/await
async function InsertAssignments(data) {
    var insertNewData = api + "/Point/insert_data/";
    await $.ajax({
        type: "POST",
        url: insertNewData + data,
        dataType: "json",
        data: data,
        timeout: 30000,
        success: function (data) {
            $("#mainGrid").data("kendoGrid").dataSource.read();
            $("#ListBox1").data("kendoListBox").dataSource.read();
            $("#ListBox2").data("kendoListBox").dataSource.read();
        },
        error: function (xhr, status, error) {
            $('#gridMessage').html(xhr.responseText).css("color", "red");
        }
    });
}

and then I’m calling InsertAssignments(data) somewhere.

Advertisement

Answer

  1. Async / await requires functions to return a promise.
  2. 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:

async function doAjax(url, params = {}, method = 'POST') {
    return $.ajax({
      url: url,
      type: method,
      dataType: 'json',
      data: params
    });
}

Then use await doAjax() whenever you are making an ajax call.

async function InsertAssignments(data) {
  const insertNewData = api + '/Point/insert_data/';
  try {
    // You can make multiple ajax calls
    // Response data is stored in result
    const result = await doAjax(insertNewData, data);
  } catch (error) {
    console.log('Error! InsertAssignments:', error);
    $('#gridMessage').html(error.message).css('color', 'red');
  }
}
Advertisement