javascript - 一个函数在 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 调用,在第一个调用完成之前。
有什么建议吗?
谢谢
解决方案
推荐阅读
- micropython - EV3 中的 Python - 安装了哪些模块?
- web-scraping - 无法运行 lambdasoup 示例
- c# - 如果绑定值为空,则 XAML/C# 隐藏 TextBlock
- jenkins-job-dsl - Jenkins DSL Plugin (>=1.77): 在 pipelineJob 中使用 gerrit-trigger
- telegram - 无法将 Cloud Foundry 应用程序(红色节点)连接到 Watson Assistant
- c++ - 指针的动态数组,如何正确执行?
- sql - 在 SQL Server 中存储比分配列更多的字符
- python - 如何序列化 Wagtail 可订购模型?
- python - Bcbio-gff 文件创建问题
- c# - C# 单元测试无法识别其他类