使用Javascript:有没有更好的办法后异步数据库X数量来执行功能/ Ajax调用 [英] Javascript: is there a better way to execute a function after x amount of async database/ajax calls
问题描述
我们有一个应用程序,在某个场合中,我们需要一个ajax后发送到客户端web服务。
using Backbone.js we have an application, in which on a certain occasion we need to send an ajax post to a clients webservice.
然而,要贴的内容,是动态的,并且是由一个特定的数组决定
however, the content to be posted, is dynamic, and is decided by a certain array.
有我们需要去获取一个数据阵列中的每一个项目。
for each item in the array we need to go fetch a piece of data.
组装需要被发送聚集的对象中的数据之后。
after assembling the data that aggregated object needs to be sent.
截至目前,我有一个同步的办法,虽然我觉得这是不是最好的方法。
as of now, i have a synchronous approach, though i feel that this is not the best way.
var arrParams = [{id: 1, processed: false},{id: 7, processed: false},{id: 4, processed: false}];
function callback(data) {
$.post()... // jquery ajax to post the data... }
function fetchData(arr, data, callback) {
var currentId = _(arr).find(function(p){ return p.processed === false; }).id; // getting the ID of the first param that has processed on false...
// ajax call fetching the results for that parameter.
$.ajax({
url: 'http://mysuperwebservice.com',
type: 'GET',
dataType: 'json',
data: {id: currentId},
success: function(serviceData) {
data[currentId] = serviceData; // insert it into the data
_(arr).find(function(p){ return p.id === currentId; }).processed = true; // set this param in the array to 'being processed'.
// if more params not processed, call this function again, else continue to callback
if(_(arr).any(function(p){ return p.processed === false }))
{
fetchData(arr, data, callback);
}
else
{
callback(data);
}
},
error: function(){ /* not important fr now, ... */ }
});
}
fetchData(arrParams, {}, callback);
是不是有启动这些异步调用和执行回调,只有当所有的结果在某种程度上?
isn't there a way to launch these calls asynchronous and execute the callback only when all results are in?
推荐答案
您必须使用jQuery $。递延
对象同步。看看这篇文章递延文档
You have to use JQuery $.Deferred
object to sync them. Look at this article Deferred Docs
您可以用此方式使用:
$.when(
$.ajax({ url : 'url1' }),
$.ajax({ url : 'url2' }) // or even more calls
).done(done_callback).fail(fail_callback);
这篇关于使用Javascript:有没有更好的办法后异步数据库X数量来执行功能/ Ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!