【问题标题】:sails.js + underscore.js failing to add hash items to an arraysails.js + underscore.js 无法将哈希项添加到数组
【发布时间】:2013-12-08 19:58:35
【问题描述】:

我正在尝试在名为“城市”的项目列表中添加一些额外的变量,然后再将其返回到我的新sails.js 应用程序中的客户端。 Sails.js 使用 Underscore.js 进行基本的函数式编程。

这是我目前使用的 _.each。 (我首先尝试使用 _.map 并返回 User 但这也不起作用)。

控制台正确记录了每个单独的用户,但在 _.each 案例“[]”中,cities_with_count 为空,而在 _.map 案例“[ undefined undefined ]”中为两个未定义的

    User.findByIdIn(user_ids).then(function(users){
    var users_with_counts = []
    _.each(users, function(user) {
      Candy.count({ type: "yummy").then(function(candy_count){
        user.candy_count = candy_count
        console.log(user);
        users_with_count.push(user);
      });
    });

    console.log(users_with_count);
    res.view({
      users: users_with_count
    });
  });

【问题讨论】:

    标签: javascript node.js underscore.js sails.js


    【解决方案1】:

    underscore 同步循环遍历用户,然后为每个用户发出一个异步请求:

    Candy.count({ type: "yummy").then(function(candy_count){
    ...
    });
    

    到 _.each 循环结束时,请求可能不一定都已处理完毕,因为无法知道回复何时来自后端以及以何种顺序。

    当代码继续时,数组 users_with_counts 尚未填充,从而导致不良行为。

    处理这些情况的一种方法是使用计数器来查看进行了多少计数查询,并仅在完成所有查询后继续执行逻辑。要么做一个 seInterval 并定期检查计数器的值,要么在填充数组后添加一个 if 条件以查看程序是否可以继续。

    但如果发生错误,您的程序将挂起,最好的长期选择是使用 promises 库,例如 q

    【讨论】:

    • 是否有强制这些计数同步的方法?
    • 不,这实际上是不可能的,节点的整个事情几乎所有来自核心和库的 API 都是同步的,这是设计使然。目标是永远不会阻塞事件线程,因为只有一个这样的线程,阻塞它会阻塞服务器。这导致代码有很多回调(参见回调地狱)stackoverflow.com/questions/18095107/callback-hell-in-nodejs 来处理到处都有异步调用。另一种方法是像 q 这样的承诺库,希望对您有所帮助。
    猜你喜欢
    • 2012-09-03
    • 2011-07-26
    • 2020-06-30
    • 1970-01-01
    • 2020-06-08
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多