我有多个Javascript函数,每个都执行一些DOM操作,然后运行一个ajax请求。我希望能够运行第一个函数,该函数操纵DOM,然后触发它的ajax请求,然后,当ajax请求完成时,如果ajax请求返回true,或者要停止执行其他的函数,我想运行第二个函数的功能和做一些其他的DOM操作(如显示错误消息)。如何顺序运行多个函数,并在其中任何一个失败时停止所有函数?
我希望这些函数能够依次运行,一个接一个地运行,并且只有在它们没有一个从它们的ajax请求返回false时才继续运行。如果它们中没有一个返回false,那么它们都应该运行,最终我会在我的“始终”回调中进行一些操作。
我该如何做到这一点?
我的第一个想法是使用承诺,以保持代码更清洁,但经过几个小时的阅读,我无法得到如何使这项工作。
下面是我当前的代码,这就是我得到了我的控制台,当它执行:
inside test1
inside test2
inside test3
fail
[arguments variable from fail method]
always
[arguments variable from always method]
这是我想在我的控制台得到(注意失踪“内TEST3”字符串) :
inside test1
inside test2
fail
[arguments variable from fail method]
always
[arguments variable from always method]
下面的代码:
(function($) {
var tasks = {
init: function() {
$.when(
this.test1(),
this.test2(),
this.test3()
).done(function() {
console.log('done');
console.log(arguments);
})
.fail(function() {
console.log('fail');
console.log(arguments);
})
.always(function() {
console.log('always');
console.log(arguments);
});
},
test1: function() {
console.log('inside test1');
return $.getJSON('https://baconipsum.com/api/?type=meat-and-filler');
},
test2: function() {
console.log('inside test2');
// note the misspelled "typ" arg to make it fail and stop execution of test3()
return $.getJSON('https://baconipsum.com/api/?typ=meat-and-filler');
},
test3: function() {
console.log('inside test3');
return $.getJSON('https://baconipsum.com/api/?type=meat-and-filler');
}
};
tasks.init();
})(jQuery)
任何想法?
This看起来像我之后...虽然我不确定胖箭头函数是否支持与常规匿名函数相同的方式?我会尝试一下,但这看起来非常棒!谢谢你,@Jaromanda X – andrux
'=>'使代码更加简洁,而且''this'的更少麻烦:p你总是可以传递上面的代码 –
我把你的代码转换成了“常规”的JS,它运行起来,记录我在控制台期待的内容:https://gist.github.com/andruxnet/11a0c2baa45e870fc449bac02cb66bf5 – andrux