2014-06-26 59 views
0

所以,我已经通过require.js构建了一个可以包含在任何JavaScript文件中的api对象。在API的对象,我也呼吁建立骨干模型/像一个集合如下图所示:如何在自定义异步函数中使用jQuery承诺?

getDatapoints: function(attributes, callback) { 
    require(['models/datapoint'], function(Datapoint){ 
     var datapoint = new Datapoint.DatapointCollection(attributes); 
     datapoint.fetch({success: function(data){ 
      return callback(data.toJSON()); 
     }}); 
    }); 
} 

我希望有能够启动多个电话和运行一个回调函数,一旦所有调用完成的方式。它看起来像jQuery的$ .when函数做我想要的,但我不知道如何让它与$ .ajax调用除外的任何工作。

我在找正确的地方吗?我应该看看类似q.js的东西吗?

+0

我不明白承诺会如何帮助。他们不是因为在一个过程中做了很多东西吗?看起来这更像是对许多进程做一件事情。说实话,当jQuery的许诺一次获取多个时,jQuery的承诺是否会迫使一个阶梯式的网络活动瀑布? – dandavis

+1

@ dandavis不一定。 '$ .when.apply($,[fetch1(),fetch2(),fetch3()])。done(dostuff)'会同时提取1 2和3,然后当所有三个都完成时,'dostuff '。这样做只需要让getDatapoints返回一个承诺,比如两个当前的答案。 –

+0

@KevinB是正确的,我的答案显示了如何做到这一点。 – idbehold

回答

1

扩大对@ mattacular的回答是:

API = { 
    getDatapoints: function (attributes){ 
    var dfd = $.Deferred(); 
    require(['models/datapoint'], function(Datapoint){ 
     var dataPoints = new Datapoint.DatapointCollection(attributes); 
     dataPoints.fetch().then(function (points){ 
     dfd.resolve(points.toJSON()); 
     }, function (error){ 
     dfd.reject(error); 
     }); 
    }); 
    return dfd.promise(); 
    }, 
    getAllDatapoints: function (arrayOfAttributes){ 
    var arrayOfPromises = arrayOfAttributes.map(this.getDatapoints); 
    return $.when.apply($, arrayOfPromises); 
    } 
} 

在哪里,你实际上调用getAllDatapoints方法:

var allDatapointAttributes = [{...}, {...}, {...}]; 
API.getAllDatapoints(allDatapointAttributes).done(function(){ 
    console.log.apply(console, arguments); 
    // should output an array of arrays containing dataPoint 
    // objects when all the requests have completed successfully. 
}); 
+0

这工作完美。谢谢! – John

0

你可以使用jQuery的Deferred对象来做到这一点。下面是一个简单的例子:

getDatapoints: function (attributes, callback() { 
    var dataPoints = $.Deferred(); 

    // perform async calls here 
    // when "done," call dataPoints.resolve() or dataPoints.reject() accordingly 

    return dataPoints.promise(); 
} 

编辑:删除过时的教程

+0

您链接的文章很旧(差不多三年)。它提到了'$ .Deferred#pipe()',我认为它不是被弃用就是被彻底抛弃了。你应该使用'$ .Deferred#then()'来代替。 – idbehold

+0

是的,很抱歉,这是我拉下的旧书签。它已经过时了。如果你有更好的链接,我会编辑我的答案,但其他人已经阐述了不同的答案,所以可能没有必要。 – mattacular