【问题标题】:Database query in loop returns only an empty array循环中的数据库查询仅返回一个空数组
【发布时间】:2019-12-04 03:53:08
【问题描述】:

'requestingUserIds' 是一个数组,具有不同的 id。每个 id 都属于表“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);````

【问题讨论】:

标签: javascript arrays node.js loops knex.js


【解决方案1】:

试试这个

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

确保它在异步函数中

【讨论】:

    【解决方案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));
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-09
      • 1970-01-01
      • 1970-01-01
      • 2012-11-25
      • 2019-01-13
      • 1970-01-01
      相关资源
      最近更新 更多