Search code examples
javascriptnode.jsknex.js

Cannot figure out how to wait for Promise


I have an array with user IDs and I need to find out what name belongs to each ID and return them in an array. I can get the user's name from the database, using knex and push them into an array, but when I try to send the data it is always an empty array.

I am not really good with Promises so can't figure out how to apply to my project.

const userId = [10,11,12,13]
let users = []

userId.map(id => {
    db.select('name').from('users').where('user_id', id)
    .then(user => {
        users.push(user)
    })
})
res.json(users)

I want the response to wait until the looping finishes and send the users array.


Solution

  • Your map is creating an array of undefined because your callback function doesn't return anything. If we tweak it slightly, it'll create an array of promises, which conveniently is exactly what Promise.all expects. :-) So:

    const userId = [10,11,12,13]
    Promise.all(
        userId.map(id => db.select('name').from('users').where('user_id', id))
    )
    .then(users => {    // `users` is an array of users, in the same order as the IDs
        res.json(users);
    })
    .catch(error => {
        // Render an error response
    });