根据两个异步函数调用的结果

时间:2016-04-11 18:49:11

标签: javascript jquery asynchronous

如果且仅当两次对异步函数的调用返回false时,我想进行表单提交。

这是简化的代码:

var firstConfirmed = false;
var secondConfirmed = false;

$form.submit(function(e) {
    e.preventDefault();

    if (!firstConfirmed) {
        firstConfirmed = getConfirmation1();    
    }

    if (!secondConfirmed) {
        secondConfirmed = getConfirmation2()
    }

    **if (firstConfirmed && secondConfirmed) { // This will get evaluated before the asynchronous calls finish :(
        $form.submit();
    }

});

getConfirmation1()getConfirmation2()是异步的:

var getConfirmation1 = function() {
    bootbox.confirm('Are you sure?', function(result) {
        if (result) {
            return true;
        } else {
            return false;
        }
    });
};

bootbox插件只等待用户输入 - 确认/取消,同样适用于getConfirmation2()

问题在于,将立即评估标有**的条件,因此表单提交无法进行。如何解决此问题并提交表单 - getConfirmation1()getConfirmation2()返回true

2 个答案:

答案 0 :(得分:2)

您可以指定一个传递给异步函数的回调函数,如下所示:

var getConfirmation1 = function(callback) {
  bootbox.confirm('Are you sure?', function(result) {
    return callback(!!result);
  });
};

...然后像这样定义回调函数:

var firstConfirmed = false;
var secondConfirmed = false;

$form.submit(function(e) {
  e.preventDefault();

  getConfirmation1(function (isConfirmed) {
    // Callback function for getConfirmation1
    firstConfirmed = isConfirmed
    checkConfirmed()
  })
  getConfirmation2(function (isConfirmed) {
    // Callback function for getConfirmation2
    secondConfirmed = isConfirmed
    checkConfirmed()
  })
});

function checkConfirmed () {
  // Return if either async function has not confirmed
  if (!firstConfirmed || !secondConfirmed) {
    return
  }
  // Both confirmed!
  $form.submit();
}

或者,您可以通过不包装引导程序调用来进一步简化您的具体示例:

var firstConfirmed = false;
var secondConfirmed = false;

$form.submit(function(e) {
  e.preventDefault();

  bootbox.confirm('Are you sure?', function(result) {
    // Callback function for first bootbox dialog
    firstConfirmed = !!result
    checkConfirmed()
  })
  bootbox.confirm('Are you sure?', function(result) {
    // Callback function for second bootbox dialog
    secondConfirmed = !!result
    checkConfirmed()
  })
});

function checkConfirmed () {
  // Return if either async function has not confirmed
  if (!firstConfirmed || !secondConfirmed) {
    return
  }
  // Both confirmed!
  $form.submit();
}

答案 1 :(得分:0)

您可以设置定期调用提交功能的计时器,也可以在确认后再次从确认对话框中调用提交功能。

实际上,我甚至不确定你的代码是否按照你的想法行事。

由于异步性质,

firstConfirmed和secondConfirmed永远不会被设置。您需要在提交函数范围之外的变量,这些变量可以通过确认对话框设置。

然后,您可以在对话框中明确设置它们

if (result) {
    firstConfirmed = true;
    doSubmitAgain();
}
相关问题