在完成特定任务之前,如何使函数不 return?

How to make a function not return until a specific task has been accomplished?

所以,我写了一个函数来模拟 JavaScript confirm 盒子的功能。

如何使函数在特定任务完成之前不 return?这里mconfirmreturnsundefined。我想 return truefalse 基于用户点击 Yes/Cancel。我该怎么做?

var mconfirm = function(message) {
    if(!message)
        message = "Remove the selected item?";
    $("#dialog-confirm").html('<span class="glyphicon glyphicon-alert" id="confirm-alert-ico"></span>&nbsp;' + message);
    $( "#dialog-confirm" ).dialog({
          resizable: false,
          modal: true,
          buttons: {
            Yes: function() {
              $( this ).dialog( "close" );
              return true;
            },
            Cancel: function() {
              $( this ).dialog( "close" );
              return false;
            }
          }  
        });
};

您不能等到这样的操作完成再返回。 (关闭对话框与从任何地方获取输入一样异步)

在 JS 中,您通常会为用户提供一种方法来传递在操作完成时调用的函数。 (即传递回调)。

var mconfirm = function(message, callback) {
if(!message)
    message = "Remove the selected item?";
$("#dialog-confirm").html('<span class="glyphicon glyphicon-alert" id="confirm-alert-ico"></span>&nbsp;' + message);
$( "#dialog-confirm" ).dialog({
      resizable: false,
      modal: true,
      buttons: {
        Yes: function() {
          $( this ).dialog( "close" );
          // Pass whatever you want to the callback
          callback("yes");
          return true;
        },
        Cancel: function() {
          $( this ).dialog( "close" );
          // Pass whatever you want to the callback
          callback("cancel");
          return false;
        }
      }  
    });
};

并且,而不是做类似的事情:

var result = mconfirm("Are you sure ?");
// result is "yes" or "cancel"

来电者会做

mconfirm("Are you sure", function(result) {
   // result is "yes" or "cancel"
});