簡體   English   中英

為什么then()鏈接的方法不能按順序運行?

[英]Why is then() chained methods not running sequentially?

我們正在嘗試以特定順序執行許多AJAX調用。 以下代碼包含methodA,methodBmethodC (每個返回運行async = true的AJAX Promise對象)。

它們使用jQuery中then()函數鏈接。

 self.methodA().then( self.methodB() ).then( self.methodC() )

我已將其中一種方法設為慢速( methodB )(我使用了慢速URL)。

我希望A ...等待10秒鍾...然后B然后C。

相反,我得到A,C .... 10秒等待,然后B。

為什么這樣做呢? 在always()函數中使用alert()與我有什么關系嗎?

這是我的小提琴代碼: http : //jsfiddle.net/h8tfrvy4/13/

碼:

function Tester() {
    var self = this;
    this.url = 'https://public.opencpu.org/ocpu/library/';
    this.slowurl = 'http://fake-response.appspot.com/?sleep=5';


    this.save = function() {
        self.methodA().then( self.methodB() ).then( self.methodC() )
    }

    this.methodA = function () {
        var self = this;

        return $.ajax({
            url: self.url,
            async: true
        }).always(function (processedDataOrXHRWrapper, textStatus, xhrWrapperOrErrorThrown) {

            //check for errors... and if OK
            alert('A OK');


        })
    }
    this.methodB = function () {
        var self = this;

        return $.ajax({
            url: self.slowurl,
            async: true
        }).always(function (processedDataOrXHRWrapper, textStatus, xhrWrapperOrErrorThrown) {

            //check for errors... and if OK
            alert('B OK');


        })
    }
    this.methodC = function () {
        var self = this;

        return $.ajax({
            url: self.url,
            async: true
        }).always(function (processedDataOrXHRWrapper, textStatus, xhrWrapperOrErrorThrown) {
            //OK
            alert('C OK');

        })
    }
}
new Tester().save();

這是錯誤的:

self.methodA().then( self.methodB() ).then( self.methodC() )

您將立即調用每種方法,並將promise傳遞給then

如果你希望每個函數等到前完成,你需要給每個then當先前的承諾,解決了一個回調來執行:

self.methodA().then(function () { return self.methodB() }).then(function() { return self.methodC() });

簡短:

this.save = function() {
    self.methodA().then( self.methodB ).then( self.methodC )
}

@meagar是正確的,這困擾着我整個**&^ * $&一天,我在這件事上是錯的,但是我確信我是正確的。 他的回答似乎太復雜了,但是早晨我頭昏腦脹,我的回答也不對。 正確的答案,當您將其插入JSFiddle時,它可以完美地工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM