如何在回调之外声明变量,在回调中修改它,然后在外面使用修改后的值?

How to declare variable outside of callback, modify it in the callback, then use modified value outside?

我正在寻找一种方法来修改在回调外部声明的变量,然后在定义回调后使用修改后的变量。我的意图体现在代码中:

$('#my_form').submit(function() {
    let my_condition
    let data = $(this).serialize()
    $.ajax({
        method: 'POST',
        url: '/my_url',
        data: data
    })
    .done(function(json_response) {
        if (json_response.my_variable) {
            my_condition = true
        }
        else {
            my_condition = false
        }
    })
    // I'm looking for a way to guarantee `my_condition` is set by the AJAX before the below code is run.
    if (my_condition) {  // I know `my_condition` will be null because this line won't wait for the AJAX to finish and set `my_condition`.
        return true
    }
    else {  // The event handler will always hit this condition.
        return false
    }
})

我知道我可以在检查 my_condition 之前添加阻塞睡眠时间以等待 AJAX。这不是我正在寻找的解决方案。我也知道我可以根据在前端检查 data 来设置 my_condition。但是,由于特定于我的用例的原因,data 需要在后端处理。最后,我想避免 AJAX 设置 async: false.

我知道为什么上面的代码不起作用。我的问题是,有什么方法可以达到预期的结果吗?我感觉可能有一个使用 Promise 的解决方案,但我不明白具体是如何实现的。

编辑 1:具体用例与表单提交有关。我希望提交处理程序为 return true 或 false,即通过表单的 action 属性(当 my_condition 为真时)或不同的 (AJAX) 路由(当 my_condition为false)根据数据后台处理结果。

编辑 2:这确实是 Javascript - Stop form submit depending on ajax response [duplicate]

的副本

我怀疑(虽然具体问题不清楚)您希望只有在 ajax 中得到有效回复后才提交表单。

您可以阻止初始提交,然后在满足条件时在 done 回调中提交表单。

$('#my_form').submit(function(e) {
    // prevent submit
    e.preventDefault()
    let form = this;
    let data = $(form).serialize()
    $.ajax({
        method: 'POST',
        url: '/my_url',
        data: data
    })
    .done(function(json_response) {
        if (json_response.my_variable) {
           // trigger native submit, will bypass this jQuery submit listener
           form.submit()
        }
        else {
            // do something else
        }
    })
 })