如果需要来自两个URL的数据,如何堆叠dojo请求

时间:2015-08-17 09:41:36

标签: javascript ajax dojo

如果需要两个来源的数据继续,我如何堆叠dojo请求函数?

以下不起作用,可能只在file1.json之后开始加载file2.json,尽管此时没有依赖:

require(["dojo/request"], function(request){
   request("file1.json", {handleAs: "json"}).then(function(datajson1){
      request("file2.json", {handleAs: "json"}).then(function(datajson2){

            use datajson1 and datajson2 here

1 个答案:

答案 0 :(得分:0)

您的两个请求都会返回给您一个承诺。 dojo/promise/all模块完全按照您的需要执行操作:等待两个Promise解析,然后您可以使用响应执行任何操作。有关all模块的详细信息,请参阅link

在你的情况下,代码应该是这样的:

require(["dojo/promise/all", "dojo/request"], function(all, request) {
    var promiseA = request("file1.json", {handleAs: "json"}),
        promiseB = request("file2.json", {handleAs: "json"});

    all([promiseA, promiseB).then(function(results) {
        // Results is the array with the promises results.
        // results[0] will be the return from promiseA
        // results[1] will be the return from promiseB
    });
}