weixin_33747129 2020-02-22 07:12 采纳率: 0%
浏览 76

jQuery异步/等待ajax调用

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.

  • 写回答

1条回答 默认 最新

  • bug^君 2020-02-22 09:11
    关注

    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) {
      try {
        return await $.ajax( {
          url: url,
          type: 'POST',
          dataType: 'json',
          data: params
        });
      } catch (error) {
        console.log(error);
      }
    }
    

    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);
      $('#gridMessage').html(error.message).css("color", "red");
     }
    
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程