json - Nodejs foreach 中的回调 hell

标签 json node.js express mongoose

我有 field 数据。我想知道现在这里的人们如何压缩 field 数据并将数据计数为 json。此代码可以运行,但 json 结果为 null。

var _venues = _.map(venues.response.venues, function (v) {
    Checkin.where({
            'venuesUniqeId': v.Id,
            'createdDate': {
                $gte: new Date().getHours() - 2
            }
        })
        .count(function (err, hereNow) {

            return new Venue({
                'uniqeId': v.id,
                'name': v.name,
                'count': hereNow
            });
        });
});
return r.json(_venues);

最佳答案

首先,很好地理解 map 函数是什么:Map 接受一组输入并将它们一对一地转换为不同的东西。在这种情况下,您的 _venues 数组为空,因为您没有在 _.map 回调中返回任何内容。

我一直解决此类问题的方法是使用像 bluebirdQ 这样的 Promise 库,并利用 .all 方法。在这种情况下,您的 _.map 不会输出实际的 _venues ,而是输出 _venuePromises ,您稍后执行并等待一系列 field 。换句话说,由于 mongoose 的异步特性,Checkin.where 的输出不是地点的集合,而是 promise 的集合。

免责声明:我不使用 mongoose,所以我不确定它如何与 Q 或 Bluebird 集成。

var Promise = require('bluebird');

var _venuePromises = _.map(venues.response.venues, function (v) {
    return Checkin.where({
            'venuesUniqeId': v.Id,
            'createdDate': {
                $gte: new Date().getHours() - 2
            }
        })
        .count(function (err, hereNow) {

            return new Venue({
                'uniqeId': v.id,
                'name': v.name,
                'count': hereNow
            });
        });
});

Promise.all(_venuePromises).then(function (actualVenues) {
  return r.json(actualVenues);
});

关于json - Nodejs foreach 中的回调 hell ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30629470/

相关文章:

node.js - Socket.io 在部署后无法工作 - 抛出错误 - 405(不允许)

json - 我在尝试从 OpenWeatherMap API 提取数据时遇到错误

javascript - 使用 angularjs 和 json wordpress api 无法访问 app.factory $resource 中的 currentPage 值

node.js - yarn 启动命令失败,退出代码为 1

javascript - ExpressJS : Promises and Error Handling middleware

node.js - 获取 "first argument must be a string or Buffer"错误

ios - 调试器只显示字典的值和键的 "(no summary)"

python - 如何从 JSON 字典设置 python 变量

node.js - 为什么在安装 npm now 包时出现此错误?

node.js - express app.use middle layer 进行身份验证