我在理解如何等待包含ajax的多个函数的结果方面遇到了问题。
我尝试过使用Promise.all()
或$.when().done();
。这些函数只在完成后调用另一个函数,我希望避免这种方法,因为它会使may代码无限复杂。我也不想在ajax调用中使用async: false
。
主函数甚至没有看起来像那样。我只需要知道是否有一个方法可以调用一个或多个具有ajax的函数,然后等待结果,而不在另一个函数中继续。
function main(){
//some functions
UploadFile('input_1');
UploadFile('input_2');
.
.
.
UploadFile('input_n');
//Here is where I want to know all the results of the UploadFile functions
//some other functions
//return true or false dependig on //some functions, UploadFile AND //some other functions
}
function UploadFile(inputId){
return $.ajax({
//ajax parameters
success: function(IDUpload) {
if (IDUpload > 0) {
return true;
}
return false;
},
error: function(error) {
return false;
}
});
}
编辑:main()
函数是表单的验证函数。似乎如果我使它异步,它就根本不会启动,它就不会等待UploadFile调用。
您可以使用await
前缀,使任何异步函数或结果同步解析,方法是停止函数,直到promise解析为成功或错误。
要使用await
前缀,您需要用async
声明包含await前缀的函数,以便运行时为等待promise的可能情况做好准备。
可在MDN文档中阅读更多信息:Await文档
// We need to define the Function as an asynchronous function, to apply await inside
async function main(e){
// Added for preventing the submit to propagate to the action-URL
e.preventDefault();
e.stopPropagation();
// As the UploadFile now only uses the synchronous Ajax-Call we can just use the returning
// result of the Function.
let res = UploadFile('input_1');
console.log(res);
// ... Other code
}
// We use the async: false Property of the Jquery Ajax Call, thous getting the response as a
// result.
function UploadFile(inputId){
let res = $.ajax({
method: "GET",
async: false,
url:"https://www.random.org/integers/?num=1&min=-10&max=10&col=1&base=10&format=plain&rnd=new",
});
// As the Ajax Call is now synchronous we have to check if the Request was successfull
// ourself. For this, we check for the Response status. Any status between 200 - 299 is
// successfull and any other has any error depending on the status code. But we wont bother
// much which error was thrown.
if(res.status >= 300 || res.status < 200) {
console.error("Request Error:", res.statusText)
return false;
}
// With the guarding If-Check before we can surely assume, the Request was successfull and
// can check now with the same logic as in the success-Method before. I've inverted the
// checks to keep consitent with the guarding If-statements.
// Same as: if(IDUpload < 0)
if(res.responseText < 0) {
console.log("The Response is not 'valid'");
return false;
}
console.log("The Response is 'valid'");
return true;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onsubmit="main(event)">
<button type="submit">Submit Form</button>
</form>