2016-09-19 50 views
3

現在我已經得到了一些代碼,發生在我想裝載等待所有功能和要求完成

的script.js

moduleLoader.load([ 
    'mainModule', 
    'aboutUsModule', 
    'featuresModule', 
    'messageModule' 
]); 

該模塊的字符串數組moduleLoader.load函數在數組上執行$.each循環,然後繼續獲取有關每個模塊的必需信息。

ModuleLoader組件

var load = function (modules) { 
    $.each(modules, function (index, module) { 
     getConfig(module); 
    }); 
}; 

getConfig

var getConfig = function (module) { 
    $.get(module + '/config.json').done(function (config) { 
     console.log(config); 
     getData(config); 
    }).fail(function() { 
     console.error('Couldn\'t find a config file for module: ' + module); 
     return 0; 
    }); 
}; 

然後你就可以在getConfig回調,它繼續得到數據,這也是異步看到的,然後它有兩個以上那是異步的步驟。

所以基本上裏面的回調回調裏面回調...等等。

只是,我把它分成功能,使它看起來更好一點。

現在我可以獲得所有的信息,但每次都會加載不同的信息,所以有可能知道所有ajax請求何時完成,然後執行某些操作?

回答

2

您可以使用jQuery的功能$.when()這不正是你所需要的: https://api.jquery.com/jquery.when/

爲了讓你的代碼工作,你可以重構一個位:

var XHRs = []; 

var load = function (modules) { 
    $.each(modules, function (index, module) { 
    XHRs.push(getConfig(module)); 
    }); 
}; 

$.when(XHRs).then(function() { 
    // do something 
}); 

,也是你的getConfig()函數應該返回$.get。這是可行的,因爲jQuery中的$ .ajax創建了一個Deferred對象,它實際上可以讓你鏈接你的函數或讓它們彼此等待。

以供將來參考: https://api.jquery.com/jquery.deferred/

+0

然後,你有一個全球'XHRs'變量? – Neal

2

您可以利用承諾鏈接,並將它們全部組合在一起,做一些事情時,他們都做(有點像這樣):

var load = function (modules) { 
    var promises = modules.map(getConfig); 

    // can use $.when or Promise.all here 
    $.when.apply($, promises).then(function() { 
     // do something when all done 
    }); 
}; 

var getConfig = function (module) { 
    // $.get returns a jqXHR which is "thennable" 
    return $.get(module + '/config.json').then(function (config) { 
     console.log(config); 
     // if this also returns a promise then it will 
     // wait till this one is done as well in the promise chain 
     return getData(config); 
    }, function() { 
     console.error('Couldn\'t find a config file for module: ' + module); 
     return 0; 
    }); 
}; 
+0

如果至少有一個請求失敗會怎麼樣?我想這會讓更多的問題,但只是說... –

+0

@ A.Wolff可能是第二個fn進入'$ .when'然後 – Neal

+0

我剛纔看到OP要求'當所有的ajax請求都完成了'所以實際上你的答案會按預期工作。我更想知道如何使用always()而不是'then(successHandler)',但是就像我剛剛說的那樣,忘記我的第一條評論;) –

0

如果你有沒有其他未決的Ajax請求,然後使用相關的全球ajax事件ajaxStop

$(document).one('ajaxStop', function() { 
    // all ajax requests has finished 
}); 
+0

但是當你停止使用jquery時,它全部壞了;-) – Neal

+0

@Neal We生活在一個愚蠢的世界肯定... –