Home > Software engineering >  javascript, nodejs await promised array
javascript, nodejs await promised array

Time:11-27

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)
        }
}


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);


CodePudding user response:

You need to return from the then block.

And spell length correctly.

You do not need to set the module scoped sorting in the then block either.

     let promisedArray = await Promise.resolve(myFunction())
     .then((realArray) => {
         sorting = realArray.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
        
         return sorting // <-- return to awaited value
      })

      for (let i = 0; i < promisedArray.length; i  ) { <-- check spelling
         console.log(promisedArray[i]) //returns the value I need
        }

You do not need await Promise.resolve either, just await realWool.

CodePudding user response:

The array sorted that you use in the loadPage function is a global variable, which means that all invocations of loadPage (I assume that each incoming request causes one invocation) will access the same array concurrently. This cannot lead to correct (or even predictable) results.

Put the let sorted = [] inside the function body to make it local. And the function must return something, for example return realWoolPromiseAsc.

  • Related