【问题标题】:Sails js -model resultset variable scopeSails js -model 结果集变量范围
【发布时间】:2017-02-14 10:33:11
【问题描述】:

有人可以向我解释为什么我不能将 booksCount 变量保存到用户 json 对象中吗?这是我的代码

for(var user in users){
    Books.count({author: users[user]['id']}).exec(function(err, count){
        users[user]['booksCount']=count;
        });
    }
return res.view('sellers', {data: users});

Users 是表中的用户列表,它是 User.find() 方法的直接结果。用户就是模型。

现在,如果我尝试在 for 循环中打印 users[user]['booksCount'],它可以正常工作。但是当它超出 for 循环时,变量就会消失得无影无踪。控制台在 for 循环外打印“未定义”。

【问题讨论】:

  • 因为你是异步的。获取所有用户时,为什么不直接填充用户书籍?
  • 这就是我所做的,1) 从书籍中获取所有作者列表 2) 填充用户数组 3) 查找每个人的书籍数量。没有作者表。用户也可以是作者。这就是我这样做的原因。
  • 谢谢,让我看看我能在这里做什么
  • 你能展示你的模型吗?

标签: node.js sails.js waterline


【解决方案1】:

因为 Books.count 是一个 API 调用并且所有的 API 调用都是异步的所以在

for(var user in users){
    // It Will call the Books.count and leave the callback Function without waiting for callback response.
    Books.count({author: users[user]['id']}).exec(function(err, count){ 
       users[user]['booksCount']=count;
    });
}
//As callback result didn't came here but the controll came here
// So, users[user] will be undefined here
return res.view('sellers', {data: users});

使用承诺:

async.forEachOf(users, function (value, user, callback) {
    Books.count({author: users[user]['id']}).exec(function(err, count){ 
           users[user]['booksCount']=count;
           callback(err);
         // callback function execute after getting the API result only
        });
}, function (err) {
    if (err) return res.serverError(err.message); // Or Error view
    // You will find the data into the users[user]
    return res.view('sellers', {data: users});
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 2013-11-12
    • 2016-12-24
    • 2012-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多