Javascript承诺递归返回索引
javascript promise return recursively to index
好的,我已经有了这样一个循环:
underscore.each(dom.paramArray, function(value, i) {
fetchDataFromServerWithParams(value, i);
});
在我当前的示例中,它循环3次,理想情况是:0,1,2然而,当我记录被调用函数的索引时,它记录的是:1,0,2,为什么?我怎样才能让它递归地调用函数呢?首先它会处理index:0的函数,然后是index:1,最后是index: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);
};
}
您可以使用async库或任何其他库来实现此目的
你也可以改变
getData.then(function (data) {
return getData.then(function (data) {
并使用此代码代替下划线循环
(function sequenceCall(index){
fetchDataFromServerWithParams(dom.paramArray[index], index).then(function(){
sequenceCall(index+1);
});
})(0);
相关文章:
- 在从索引位置返回的字符串中查找空白
- 使用共享工具提示时,单击Highcharts柱形图会返回不正确的序列索引
- 如何比较两个数组,然后返回差异的索引
- 在 jquery 选项卡中查找 span 标记并返回该索引
- 如何获取从循环返回的元素的索引
- 需要呈现MongoDB查询返回结果的特定索引/位置
- 通过getElementById查找所选索引是't返回正确的值
- 按流星空格键模板中的索引返回数组项
- 辅助功能键盘专用选项卡到z索引“;返回顶部”;
- JavaScript:通过其他数组元素的索引访问ArrayElement?array[array[0]返回undefin
- 如果我对索引进行硬编码,它会按预期工作,为什么这个增量器会返回NAN
- 为什么不't此循环返回到第一个索引
- .children()不适用于jquery返回的指定索引
- 角度:通过数组查找其索引返回对象的内容
- 如何使用此图像轮播的索引返回实际图像
- 为什么警报在 JS 中不起作用,索引返回 -1
- 获取空格索引返回错误的值
- JavaScript正则表达式匹配将输入作为前两个索引返回
- 为什么二维数组的索引返回-1
- 按索引返回数组值,如果给定else,则返回数组