我对AJAX调用还不太熟悉,无法知道它是如何工作的。
如果我有一个数组A并且在上面使用A.filter()
,那么过滤器中的AJAX调用将如何工作?我相信,该数组用于同步填充模板。
// Event calls function to filter list on page.
// Function calls filterArray(arrayList, objFilters)
async_fetch: function(string)
{
// Utilizes $.ajax() to retrieve a JSON array
var deferred = $.Deferred();
$.ajax({
url: ...,
dataType: "json",
success: function(data) {
var response = data;
deferred.resolve(data);
},
error: function(data)
{
//...
deferred.reject(msg);
}
});
return deferred;
};
filterArray: function(list, filters)
{
var filteredList = list.filter(function(item) {
for(var key in filters) {
// Actions for each of multiple filters to compare against...
else if(key == 'FILTER_X') {
var data = async_fetch(item.name);
// Use data to arrive at a determination, where true means I don't want to include this item in the filtered list
if(determination)
return false;
}
}
};
return filteredList;
};
// Results of filterArray() are passed along to a template within Backbone
// to redraw a segment of HTML on the page.
过滤器调用将仅同步等待AJAX调用完成吗?列表是否会被过滤掉并返回,并且AJAX调用必须挂接到过滤后的列表中,并且稍后实质上完成过滤?
我应该只构建一个不是异步的async_fetch()
版本吗?
答案 0 :(得分:1)
async_fetch(item.name).then(function(data){
if (data.determination)
// do something
})
....
答案 1 :(得分:0)
您好,您可以在过滤数据后解决承诺。 像这样的例子 希望对您有帮助。
$(document).ready(function(){
function async_fetch(string)
{
// Utilizes $.ajax() to retrieve a JSON array
var deferred = $.Deferred();
$.ajax({
url: string,//your URL
dataType: "json",
success: function(data) {
var filterdData= filterArray(data);
deferred.resolve(filterdData);
},
error: function(data)
{
//...
deferred.reject(msg);
}
});
return deferred;
};
function filterArray(data)
{
var filteredList = data.filter(function(item) {
//filter whatever you want
})
return filteredList;
}
async_fetch(url).then(function(response){
//now you will get the filterd data
console.log(response);
})
});
答案 2 :(得分:0)
您可以在async/await
的帮助下进行以下操作:-
const filterArray = async function (list, filters) {
var filteredListPromise = list.filter(async function (item) {
for (var key in filters) {
// Actions for each of multiple filters to compare against...
if (key == 'FILTER_X') {
return arriveAtDetermination(item.name);
}
else {
//other filters
}
}
});
return Promise.all(filteredListPromise);
};
async function arriveAtDetermination(name) {
let data = await async_fetch(name);
return determination ? true : false;//your logic
}
//Now you can filter like
filterArray(list, filters).then(result => {
console.log(result);
}).catch(err => {
console.log(err);
})