I have a problem with promised array: I'm calling inside my switch a function which is loading an array from API Example:
let sorted = []
let limit = 10
async function loadPage(slcLimit) {
let i
let filter = document.getElementById("show-filter").value
if (sorted.length == 0) {
switch (filter) {
case "1":
let realWoolPromiseAsc = await Promise.resolve(realWool(pagingPouches))
.then((realWoolArr) => {
sorted = realWoolArr.sort((a, b) => parseFloat(a.realWool) - parseFloat(b.realWool));
return sorted
})
break;
case "2":
let realWoolPromiseDesc = await Promise.resolve(realWool(pagingPouches))
.then((realWoolArr) => {
sorted = realWoolArr.sort((a, b) => parseFloat(b.realWool) - parseFloat(a.realWool));
return sorted
})
break;
}
}
for (i = startingLimit; i < (startingLimit + limit); i++) {
console.log(sorted[i].ID + " - " + sorted[i].price)
}
}
Real wool function
window.realWool = async function realWool(pouchArr) {
let divider = 1000000000000000000n;
let realWoolArray = []
pouchArr.forEach(async pouch => {
let availAmount = await pouchContract.amountAvailable(pouch.pouchID)
availAmount = Number(BigInt(availAmount.toString()) * 100n / divider) / 100
availAmount = Math.floor(availAmount * 100) / 100
let rWool = pouch.pouchWool - availAmount
realWoolArray.push({pouchID: pouch.pouchID, realWool: rWool, pouchTime: pouch.pouchTime})
//document.getElementById("lockedText" + pouch.pouchID).innerHTML = "Real WOOL: <span class='black'>" + rWool + "</span>"
});
return realWoolArray
}
I need to use the sorting array inside my for loop but I'm getting undefined. I understand I need to use await or a then block I just have no clue how to use that.
Thank you!
I've used a timeout, but it is not optimal since sometimes the function just return an array of 5 objects and sometimes a hundreds of objects (depends on filters)
setTimeout(() => {
for (i = startingLimit; i < (startingLimit + limit); i++) {
console.log(sorted[i].ID + " - " + sorted[i].price)
}
}, 5000);