node.js - Sails js -模型结果集变量范围

标签 node.js sails.js waterline

有人可以向我解释为什么我无法将 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 循环外部打印“未定义”。

最佳答案

因为 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});

使用 promise :

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

关于node.js - Sails js -模型结果集变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42223792/

相关文章:

node.js - fs.writeFile() 是否处理 Nodejs 中的竞争条件?

javascript - 如何 AJAX POST 对象数组到 Node.js 服务器?

javascript - Sails.js 模型 updatedAt (updated_at) 不自动更新

javascript - 水线包含关联属性?

javascript - Sails.js 简单的私有(private)消息传递(发布/订阅和模型)

javascript - 使 sails.js 水线大小写敏感

node.js - sails/水线 : How to retrieve relations inside a relation?

node.js - 如何让函数调用等待另一个函数调用完成

javascript - 使用 Multer 上传多个文件

sails.js - 如何在 Sails js 中为模型属性设置索引?