Jquery async/await ajax call

10,666

Async/await requires functions to return a promise. $.ajax() in your code is using callback, not a promise.

Wrap $.ajax() in a function like this:

async function doAjax(url, params, method) {
    return $.ajax( {
      url: url,
      type: method || 'POST',
      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');
  }
}

Edit: redundancy in the code has been removed based on Oleg's comment.

Share:
10,666

Related videos on Youtube

davis
Author by

davis

Updated on June 04, 2022

Comments

  • davis
    davis almost 2 years

    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.

    • CertainPerformance
      CertainPerformance about 4 years
      That looks like one request. Where are the other two?
    • CertainPerformance
      CertainPerformance about 4 years
      Can you respond? It's unclear which 3 requests you're referring to
    • davis
      davis about 4 years
      The other two are working just fine. I do not need add async:false in them. I only just want async/await in this ajax method.
  • davis
    davis about 4 years
    Thank you so much. I think this is pretty close to what I really want. I'm trying to use this, but still I don't think I understood well enough. Now I know async/await requires two parts. Can you please check these? So the promise part, this is what I have. async function WaitAssignmentAjax(url, params) { const insertNewData = api + "\Point/insert_data/"; try { return await $.ajax({ type: "POST", url : insertNewData + params, dataType: "json", data: params }); } catch (error) { alert(error); }
  • davis
    davis about 4 years
    async function InsertAssignments (data) { const insertAssignments = const insertNewData = api + "/Point/insert_data/"; try { const result = await WaitAssignmentAjax(insertNewData, params); } catch (error) { $('#gridMessage').html(error.message).css("color", "red"); });
  • davis
    davis about 4 years
    Sorry it looks really messy here. But if I use do await WaitAssignments(); somewhere in my code that I want this to be executed, it says await has to be in async function. Where can I call await WaitAssignments(); ? in the async function InsertAssignments(data)? I'm sorry this is my first time using it so I'm confused
  • davis
    davis about 4 years
    Sorry for the previous silly questions. I finally got it working! I just changed all 3 ajax calls to async/await functions and they are working great! Feels so good that I learned something cool haha. I could have just put async:false as an easy/quick fix, but I wanted to handle it properly. Thank you so much for your help though.
  • Oleg Valter is with Ukraine
    Oleg Valter is with Ukraine over 3 years
    Please note that return await is redundant since the function with async keyword returns a Promise regardless and any calling code will have to await the resulting Promise (unless you really need to handle the rejection inside the doAjax [i.e. one or more of the calls failing is expected] - which, given the calling code is already wrapped in try...catch seems to not be necessary).