等待AJAX从函数返回前完成? [英] Wait for AJAX to complete before returning from function?
问题描述
我有以下
function doAjax()
{
var result = false;
$.ajax(url, data)
.done(function(){
// Do a bunch
// of computation
// blah blah blah
result = true;
}).fail(function(){
result = false;
});
return result;
}
function doSomething()
{
if ( doAjax() == true )
console.log('success');
else
console.log('failed');
}
function doSomethingElse()
{
if ( doAjax() == true )
console.log('success');
else
console.log('failed');
}
我有运行一些Ajax功能,然后返回true或false,这取决于是否AJAX的成功与否。这AJAX功能,我从多个地方在我的code调用。
I have a function that runs some ajax, then returns true or false, depending on whether the ajax was successful or not. This ajax function I call from multiple places in my code.
由于该函数的AJAX完成之前结束,它总是返回false。我该如何避免这种情况?
Because the function ends before the ajax finishes, it always returns false. How do I avoid this?
我看过的东西暗示我做了返回我的功能$。阿贾克斯()
然后移动 .done()
和 .fail()
功能,我的 DoSomething的()
和 doSomethingElse ()
功能。然而,在我的 .done()
的方法,我计算了一堆。很多code。所以,问题是,如果我移动 .done()
功能,我的其他功能,我复制了一堆code。
I have read something suggesting that I do a return $.ajax()
in my function and then move the .done()
and .fail()
functions to my doSomething()
and doSomethingElse()
functions. However, in my .done()
method, I do a BUNCH of computation. Lots of code. So the problem is, that if I move the .done()
function to my other functions, I am duplicating a bunch of code.
我如何避免这种情况?只是包装计算到它自己的功能,并调用它在必要?
How do I avoid this? Just wrap the computation into it's own function and call it wherever necessary?
推荐答案
调整你的code使用的回调,而不是回报,像这样...
Restructure your code to use callbacks instead of returns, like this...
function doAjax(callback)
{
$.ajax(url, data)
.done(function(){
// Do a bunch
// of computation
// blah blah blah
callback(true);
}).fail(function(){
callback(false);
});
}
function doSomething()
{
doAjax(function(result){
if (result == true )
console.log('success');
else
console.log('failed');
});
}
function doSomethingElse()
{
doAjax(function(result){
if (result == true )
console.log('success');
else
console.log('failed');
});
}
这篇关于等待AJAX从函数返回前完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!