循环中的数据库查询 returns 只有一个空数组

Database query in loop returns only an empty array

'requestingUserIds' 是一个数组,有不同的id。每个 id 都属于 table 'users' 中的一个用户名。这就是为什么我要循环,对于数组 'requestingUserIds' 中的每个 id,将相应的用户名放入数组 'requestingUserUsernames' 中,最后将完整数组 (requestingUserUsernames) 记录到控制台中。但是如果我在then函数之外做,只会输出一个空数组,可能是我一开始发起的数组。

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

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

确保它在异步函数中

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

这也有效,但我不确定它是否像下面那样干净。