首页 > 解决方案 > 一个函数在 Javascript (AJAX) 中等待另一个函数

问题描述

我试图找到一种方法使一个函数保持不变,并且仅在其中的异步函数(AJAX 调用)完成时才返回其输出(保持流)。

在此单击事件中,“prepareEstimates”函数调用另一个函数,该函数对 API 进行 AJAX 调用。这个想法是代码不会继续前进,直到这个函数完成所有的事情,包括 AJAX 调用。因为它调用的是同一个 API,所以我不能同时调用两个使用相同的数据(API 的问题超出了这个问题的范围)。

 $('#estimateBtn').on("click", function () {
        if (validateBasicEstimationForm()) {
            prepareEstimates();

                if (validateCustomEstimationForm()) {
                    prepareCustomEstimates();
                } 

});
function prepareEstimates() {

   // check if runAPI should be true or false

    if (runApi) {
        // make call here
        $.when(callAJAXFunction(path, dataForAPICalls)).done(function (result) {
          // Do stuff with the result
        });
    }
};

然后,一旦这个 prepareEstimates 函数完成,它应该继续前进,下一个与这个函数非常相似的 prepareCustomEstimates 将做同样的事情。

function prepareEstimates() {

   // check if runAPI should be true or false

    if (runApi) {
        // make call here
        $.when(callAJAXFunction(path, dataForAPICalls)).done(function (result) {
          // Do other stuff with the result
        });
    }
};

而这个 callAJAXFunction 只返回一个 AJAX 调用

    // Invoke API call and get result
    return await $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        data: data,
        success: function (result) {
        },
        error: function () {
            console.log("error calling Api");
        }
    });
}

我尝试使用 promise、await 和其他方法,但无论我尝试什么,我都无法让它工作。

最后,发生的事情是第一个 AJAX 调用被触发,然后在它之后,第二个 ajax 调用,在第一个调用完成之前。

有什么建议吗?

谢谢

标签: javascriptjqueryajaxasynchronousasync-await

解决方案


推荐阅读