N
N
Nikita Andreevich2020-12-11 15:48:01
JavaScript
Nikita Andreevich, 2020-12-11 15:48:01

How to make nested asynchronous requests?

Hello.
At first glance, the task seemed simple to me, but I have been sitting on it for 2 hours.

I write rest api on node js.

There is a router (express) that takes 2 parameters in the request field (query params) ->

http://localhost:5000/api/item/?title=new task&user_id=1


I get these parameters on the server ->
router.get('/', async (req, res) => { 
const {title,user_id} = req.query
})


Next, I need to get all matches from the database using these parameters.
router.get('/', async (req, res) => { 
const {title,user_id} = req.query
const items = await Item.findAll({ where: { title, user_id } })
})

and then you need to run the items array through the loop and at each iteration get items -> user_id from each element, make a query to the database and get certain data about the user who created this item, and ultimately an array with items objects (+ plus for each item added user data) returned to the client.

I was expecting something like this:

let result = await items.map(async (item) => {
      const { title, phone, name, email } = await User.findByPk(item.user_id)
      return {
        id: item.id,
        title: item.title,
        price: item.price,
        image: item.image,
        createdAt: item.createdAt,
        user: { title, phone, name, email }
      }
    })
    res.json({ valid: true, data: result })


But due to the fact that asynchrony occurs in the loop, a promise is returned at each iteration, as a result, I get this result:
"data": [
        {}
    ]


Tried await, then, callback

Tell me how to solve this problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nicholas, 2020-12-13
@NikitosAndreevich

The problem is with await items.map(...)
map returns an array - not a promise - no waiting happens. You can, as advised above, not use .map, or use Promise.all:

let result = await Promise.all(items.map(async (item) => {}))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question