我有两个JS函数flowA()
和flowB()
,它们都调用Ajax fetch函数,定义如下:
function ajaxGetQuestions() {
$.ajax( {
// DB call..
}).done({
// Build a DOM structure with results...
});
}
flowA()
在没有任何额外的情况下调用此方法。flowB()
需要调用此方法,并修改成功回调创建的其中一个元素。我应该如何构建我的代码和jQuery承诺?
显然我不想做
function flowA() {
ajaxGetQuestions();
}
function flowB() {
ajaxQuestions();
extraSteps();
}
有了承诺,我不想连接任何.done回调。 Ajax函数共享(可重用),只做一件事。在可重用的Ajax代码完成之后,由外部流程B完成额外的工作。
答案 0 :(得分:2)
function ajaxGetQuestions() {
return $.ajax( { // this returns a promise
// DB call..
}).done({
// Build a DOM structure with results...
});
}
然后
function flowA() {
ajaxGetQuestions();
}
function flowB() {
ajaxQuestions()
.then(extraSteps);
}
承诺非常适合这种任务! ; O)