关于 Ajax 和 promise 的新手问题。
我有两个 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 代码完成后,由外部 Flow B 来做它额外的事情。
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);
}
Promise 非常适合这种任务!;o)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句