1

I have an array of category ids in order, I have to make a map and fetch the items from these categories and in the end keep the original order of the array

what I've been doing:

const info = []
Promise.all(categoryItem.next_steps.map((next_step) => {
   return categoryItemSvcV2.getAllItensNoOrderByCategoryId(next_step.category, idpage)
       .then((result) => {
            info.push(result)
       })
})).then(() => {
   res.json({ success: true, info })
})

the categoryItem.next_steps is the array of categoryIds on order, however each time I call this function it displays in an order

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Thyi
  • 59
  • 1
  • 6
  • 1
    Do not push to an array outside of a promise. It will only bring you pain – evolutionxbox May 06 '22 at 14:33
  • 1
    Does this answer your question? [How to return value from an asynchronous callback function?](https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – evolutionxbox May 06 '22 at 14:33

2 Answers2

1

Promise.all does this out of the box, don't bring your own array:

Promise.all(categoryItem.next_steps.map(next_step =>
  categoryItemSvcV2.getAllItensNoOrderByCategoryId(next_step.category, idpage)
)).then(info => {
//      ^^^^
   res.json({ success: true, info })
});
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

As you're using Promise.all, you don't need to create a separate array. Looking at your code above, this should work

const values = await Promise.all(
  categoryItem.next_steps.map((next_step) =>
    categoryItemSvcV2.getAllItensNoOrderByCategoryId(next_step.category, idpage)
  )
);

res.json({ success: true, values });

Inder
  • 1,711
  • 1
  • 3
  • 9