两个流调用Ajax方法,最后需要额外的处理

时间:2017-12-10 16:18:58

标签: javascript jquery ajax promise

关于Ajax和承诺的新手问题。

我有两个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完成额外的工作。

1 个答案:

答案 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)