我有以下内容
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 函数。
因为该函数在 ajax 完成之前结束,所以它总是返回 false。我该如何避免这种情况?
我读过一些建议我做的事情return $.ajax()
在我的函数中,然后移动.done()
and .fail()
对我的功能doSomething()
and doSomethingElse()
功能。然而,在我的.done()
方法,我做了一堆计算。很多代码。所以问题是,如果我移动.done()
函数到我的其他函数,我复制了一堆代码。
我该如何避免这种情况?只需将计算包装到它自己的函数中并在必要时调用它?
重构您的代码以使用回调而不是返回,就像这样......
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');
});
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)