javascript - jQuery promise 出现意外的 "then"调用顺序

标签 javascript jquery typescript promise

我使用 jQuery Promise 来跟踪服务器上的一些更改。我也使用 typescript ,所以我的例子是 typescript 。

我使用以下方法来跟踪更改:

startObserve(): JQueryPromise<void> {
    console.info("initializing...");

    const that = this;
    let countdown = 3;

    return this.loadData()
        .then(baseData => {
            const checkChanges = () => {
                const d = $.Deferred();
                d.then(() => {
                    console.info("checking changes...");

                    return that.loadData()
                        .then(data => {
                            countdown--; // emulate check logic

                            console.info("next interation! countdown:", countdown);

                            if (countdown === 0)
                                return null;

                            return checkChanges();
                        });
                });
                setTimeout(d.resolve, 250);
                return d.promise();
            };

            return checkChanges();
        });
}

所以我只是递归调用 checkChanges 方法,该方法返回新的 promise ,直到检测到某些更改。

以下是我尝试使用 startObserve 方法的方法:

    this.startObserve()
        .then(() => {
            console.info("change detected! we can continue!");
        }).fail(() => {
            console.error("something is very wrong!");
        });

我期望得到以下输出:

initializing...
checking changes...
next interation! countdown: 2
checking changes...
next interation! countdown: 1
checking changes...
next interation! countdown: 0
**change detected! we can continue!**

但这就是我得到的:

initializing...
checking changes...
**change detected! we can continue!**
next interation! countdown: 2
checking changes...
next interation! countdown: 1
checking changes...
next interation! countdown: 0 

对我来说,这看起来有点奇怪。我哪里错了?这是显示问题的 jsfiddle:https://jsfiddle.net/4dofznqL/1/

最佳答案

您返回的是通过超时解决的 promise ,而不是链接 ajax promise :

...

const checkChanges = () => {
  const d = $.Deferred();
  setTimeout(d.resolve, 250);

  return d.then(() => {
    console.info("checking changes...");

    return that.loadData()
      .then(data => {
      countdown--;

      console.info("next interation! countdown:", countdown);

      if (countdown === 0)
        return null;

      return checkChanges();
    });
  });
};

...

关于javascript - jQuery promise 出现意外的 "then"调用顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44869908/

相关文章:

javascript - Jscript 不打印到元素

javascript - 如何使用 jQuery 创建动态表单

跨多个容器或父级的 jQuery UI 可排序 div

javascript - 使用 Canvas 的倒计时器

jquery - wrapbootstrap jquery 不能与 angularjs 一起使用

javascript - 根据数组元素调用函数

javascript - 如何使用 TypeScript 键入类似 jQuery 的初始化模式?

typescript - 使用reduce从对象数组创建强类型TS字典

angular - 为什么 $app-direction : rtl not working?

javascript - 选择类选择器子div Jquery