【问题标题】:No length on promise没有承诺的长度
【发布时间】:2015-10-14 06:40:44
【问题描述】:

我有这个代码:

exports.calculate = function(req, res, next) {
    statistics.commented_quizes = 0;
    statistics.no_commented = 0;
    Promise.all([
        models.Quiz.count(),
        models.Comment.count(),
        models.Quiz.findAll({
            include: [{
                model: models.Comment
            }]
        })
    ]).then(function(results) {                                 // `results` is an array of [quizes, comments, all]
        statistics.quizes               = results[0];
        statistics.comments             = results[1];
        statistics.average_comments     = (statistics.comments / statistics.quizes).toFixed(2);
        for (index in results[2]) {
            if (results[2][index].Comment.length) {
                statistics.commented_quizes++;
            } else {
                statistics.no_commented++;
            }
        }
    }).then(next, next);
};

此代码无法读取未定义的长度属性,在本例中为“注释”。

怎么了?我试图删除该属性,但结果无法正常工作,所以我需要识别错误,但我不明白。

提前致谢!

【问题讨论】:

  • results[2][index] 中的实际内容是什么?记录results[2] 并检查。我想知道这不是因为区分大小写的属性(comment,而不是Comment)。
  • results[2][index] 为空!什么都没有创建。注释是数据表的名称。我试图通过评论更改它,但它不起作用。对不起,我的英语不太好。
  • 对不起,但这没有任何意义。如果您的代码在 results[2][index] 行上失败,则 results var is 在那里定义。检查您放置日志记录行的位置,然后重试。
  • 这个问题真的和 promises 没什么关系,所以这个标题很容易误导。问题完全在于results[2] 中的内容以及如何正确迭代它以获得您正在寻找的任何内容。如果您发布 console.log(results[2]) 的结果,我们都可以提供更好的帮助。

标签: javascript node.js promise


【解决方案1】:

回答我的问题...

我终于找到了错误。长度不属于 Comment,而是属于 cmets。

很抱歉给您带来不便。

exports.calculate = function(req, res, next) {
    statistics.commented_quizes = 0;
    statistics.no_commented = 0;
    Promise.all([
        models.Quiz.count(),
        models.Comment.count(),
        models.Quiz.findAll({
            include: [{
                model: models.Comment
            }]
        })
    ]).then(function(results) {                                 // `results` is an array of [quizes, comments, all]
        statistics.quizes               = results[0];
        statistics.comments             = results[1];
        statistics.average_comments     = (statistics.comments / statistics.quizes).toFixed(2);
        for (var i in results[2]) {
            if (results[2][i].comments.length) {
                statistics.commented_quizes++;
            } else {
                statistics.no_commented++;
            }
        }
    }).then(next, next);
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多