好的,所以我有一个这样的循环:
underscore.each(dom.paramArray, function(value, i) {
fetchDataFromServerWithParams(value, i);
});
在我目前的例子中,它循环3次,理想情况如下:0,1,2 但是,当我记录被调用函数的索引时,它会记录:1,0,2,为什么? 我怎样才能让它以递归方式调用函数,所以首先它将处理函数的索引:0,然后索引:1,最后,索引:2
我认为它与我调用的函数(buildResult和buildSubResult)有关,但我真的不确定?
循环调用的函数如下所示:
function fetchDataFromServerWithParams(param, index) {
//Create promise
let getData = $.ajax({
headers: {
Accept : "text/plain; charset=utf-8",
"Content-Type": "text/plain; charset=utf-8"
},
type: "GET",
url: configuration.apiEndpoint,
data: { id: param},
dataType: "json"
});
//When done processing promise, build result
getData.then(function (data) {
let generatedData;
console.log(index);
if(index === 0) {
generatedData = buildResult(data);
} else {
$.each($("ul.material a"), function( index, value ) {
var target = $(this).parent();
if($(this).data("id") == param) { //Refactor later to ===
target.parent().addClass("open-folder");
target.parent().parent().find("ul").addClass("open-folder");
generatedData = buildSubResult(data, target);
}
});
}
}), function(xhr, status, error) {
// Handle errors for any of the actions
handleError(error);
};
}
答案 0 :(得分:0)
您可以使用async库或任何其他库来实现此目的
你也可以改行
getData.then(function (data) {
到
return getData.then(function (data) {
并使用此代码代替您的下划线循环
(function sequenceCall(index){
fetchDataFromServerWithParams(dom.paramArray[index], index).then(function(){
sequenceCall(index+1);
});
})(0);