意外的"然后"用jQuery承诺调用命令

时间:2017-07-02 10:41:00

标签: javascript jquery typescript promise

我使用jQuery promises来跟踪服务器上的一些更改。我也使用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/

1 个答案:

答案 0 :(得分:3)

你通过超时而不是链接ajax承诺来回复承诺:

ERROR Error: SignalR: Connection has not been fully initialized. Use 
.start().done() or .start().fail() to run logic after the connection has 
started.