I need to loop through an array of items and check if each item's type matches desired type. Once all the checking are done, add the ones that meet requirement to a dropdown select box. In an array where 2 items meet the requirement, this code checks is only adding the first item to the dropdown always, what is wrong with it?
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);
});
EDIT: someone pointed out that I need to use each
instead of forloop to make a closure, I tried it but still does not work. I tried doing
$.each(items, function(index){...}
and
items.forEach(function(index){...}
and modified what's inside the loop accordingly but no luck. This post (JavaScript closure inside loops – simple practical example) does not help me.