Database query in loop returns only an empty array

六眼飞鱼酱① 提交于 2019-12-02 16:19:25

问题


'requestingUserIds' is an array, with different ids. Each id belongs to a username in the table 'users'. That's why I want to loop, for each id in the array 'requestingUserIds', the corresponding username into the array 'requestingUserUsernames' and finally log the full array (requestingUserUsernames) into the console. But if I do it outside the then function, only an empty array is output, probably the array I initiated in the beginning.

When i log the array 'requestingUserUsernames' inside the then function in the console, the array gets outputted for each loop pass, but i only want to output the final array.

requestingUserIds.forEach(userId => {
    db('users')
        .select('username')
        .where({id: userId})
        .then(rows => {
            requestingUserUsernames.push(rows[0].username);
         })
         .catch(error => console.log(error));
});
console.log(requestingUserUsernames);````

回答1:


try this

const requestingUserUsernames = await Promise.all(requestingUserIds.map(userId =>
    db('users')
        .select('username')
        .where({id: userId})
        .then(rows => rows[0].username)));
console.log(requestingUserUsernames);

Make sure it is in an async function




回答2:


requestingUserIds.forEach(userId => {
    db('users')
        .select('username')
        .where({id: userId})
        .then(rows => {
            requestingUserUsernames.push(rows[0].username);
            if (requestingUserUsernames.length ==  requestingUserIds.length) {
                console.log(requestingUserUsernames);
            }                                
    })
    .catch(error => console.log(error));

This also worked, but im not sure if it is as clean as below.



来源:https://stackoverflow.com/questions/57209251/database-query-in-loop-returns-only-an-empty-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!