等待异步调用完成 - 太晚了

Wait for asyn call to finish - too late

我有一个带有按钮的对话框。单击该按钮后,该按钮将调用一个异步方法,该方法 returns true 或 false 取决于发布的数据是否有效。 点击事件调用下面的方法。 现在,问题是在执行回调函数之前调用了 closeDialog! 我怎样才能完成这项工作?

谢谢

close: function (srcCmd) {
   var closeResult = true;
   asyncThing(function(result) {
      if (result)
         closeResult = true;
      else
         closeResult = false;
   }); 

   if (closeResult !== false) {
       this.closeDialog();
   }
},

你应该看看使用 promise。 JQuery Ajax 原生调用 return Promise。

EG:

$.ajax(ajaxObj).success(function(resp) { console.log('I have completed');});

将对话框关闭放在调用的成功或失败部分。

异步调用完成时(无论何时)调用带有 asyncThing 的函数。所以这不会逐行解释。

把后面的if问题移到回调函数就可以了。

close: function (srcCmd) {
   var closeResult = true;
   asyncThing(function(result) {
       if (result)
           closeResult = true;
       else
           closeResult = false;
    if (closeResult !== false) {
       this.closeDialog();
    }
  });
},

根据您的代码片段,它应该如下所示:

close: function (srcCmd) {
   var closeResult = true;
   asyncThing(function(result) {
      if (result)
         this.closeDialog();

   }); 
},

在你的版本中这段代码

if (closeResult !== false) {
    this.closeDialog();
}

在调用 asyncThing 的回调之前被调用。这就是对话框 closeDialog 被调用的原因

这是因为这段代码的异步部分在回调函数中。然后您在同步部分调用关闭对话框,该部分在发送请求后立即运行。 只需将调用移至回调即可。

如前所述,您还需要在回调函数中处理 this,因为 js 在运行时确定 this。所以它并不总是对你的对象的引用。

一种方法是在回调之外的另一个变量中缓存 this

close: function (srcCmd) {
   var self = this;
   var closeResult = true;
   asyncThing(function(result) {
      if (result)
         closeResult = true;
         self.closeDialog();
      else
         closeResult = false;
   }); 
},

另一种方法是使用其中一种绑定方法(.bind、.call、.apply):

close: function (srcCmd) {
   var closeResult = true;
   asyncThing(function(result) {
      if (result)
         closeResult = true;
         this.closeDialog();
      else
         closeResult = false;
   }.bind(this)); 
},

还有一个用于处理异步的 Promise 模式。但是更难正确使用。