循环中的数据库查询仅返回一个空数组 [英] Database query in loop returns only an empty array

查看:138
本文介绍了循环中的数据库查询仅返回一个空数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

'requestingUserIds'是一个具有不同ID的数组.每个ID都属于用户"表中的一个用户名.这就是为什么我要针对数组"requestingUserIds"中的每个id将对应的用户名循环到数组"requestingUserUsernames"中,并最终将完整的数组(requestingUserUsernames)记录到控制台中.但是,如果我在then函数之外执行此操作,则只会输出一个空数组,可能是我一开始就启动的数组.

'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.

当我在控制台的then函数中记录数组'requestingUserUsernames'时,每次循环传递都会输出该数组,但是我只想输出最终数组.

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

推荐答案

尝试一下

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

确保它在异步功能中

这篇关于循环中的数据库查询仅返回一个空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆