我需要循环通过一系列项目,并检查每个项目的类型是否匹配所需的类型。完成所有检查后,将满足需求的订单添加到下拉式选择框中。在2个项目满足要求的数组中,此代码检查仅将第一个项目添加到下拉列表中,该项目始终是什么问题?
var promises = [];
var html = "";
for (var i = 0; i < items.length; i++) {
var promise = new Promise(function(resolve, reject){
$.ajax({
url: "url" + items[i],
dataType: "json",
success: function (data) {
console.log(data);
console.log(data.type); // "mytype"
console.log(typeof data.type); // string
if(data.type == "mytype") {
html += "<option value='" + data.id + "'>" + items[i] + "</option>";
resolve();
}
}
});
promises.push(promise);
});
}
console.log(promises) // (2) [undefined, Promise]
Promise.all(promises).then(() => {
$("#dropdownBox").html(html);
});
编辑:有人指出,我需要使用each
而不是forloop进行封闭,我尝试了它,但仍然不起作用。我尝试做
$.each(items, function(index){...}
和
items.forEach(function(index){...}
并相应地修改了循环内部的内容,但没有运气。这篇文章(JavaScript封闭循环 - 简单实践的例子)对我无济于事。
您遇到的问题之一是如果类型不满足条件,则不能解决承诺。
您的for()
循环也不会创建关闭,因此i
不会是您期望的,请求完成
由于 $.ajax
返回承诺,这是一种使用map()创建闭合和承诺数组
// map array of promises
var promises = items.map((item) => {
// return $.ajax promise
return $.ajax({
url: "url" + item,
dataType: "json"
}).then((data) => {
let html = '';
if (data.type == "mytype") {
html += "<option value='" + data.id + "'>" + item + "</option>";
}
return html;
});
});
Promise.all(promises).then((res) => {
// res is array of html (or empty) strings returned in each then() above
$("#dropdownBox").html(res.join(''));
}).catch(err => console.log('At least one request failed'));
demo