【问题标题】:Node Express Handlebars helper not returning result of functionNode Express Handlebars 助手不返回函数结果
【发布时间】:2015-05-25 16:43:08
【问题描述】:

我对这个感到困惑。如果我在车把助手中使用函数并返回该函数的结果,则不会返回任何内容。

这是模板:

<ul>
    <li>{{formatid this.id}}</li>
</ul>

这是助手:

formatid : function(id){
    mOrders.formatOrderID(id, function(err, formatted_id){
        // err is always null, no need to handle
        console.log(formatted_id);
        return formatted_id;
    });
}

尽管正确的文本被记录到控制台,生成的 html 是:

<ul>
    <li></li>
</ul>

但是,如果我在 formatOrderID() 函数的末尾添加了一个 return,它就会被返回,所以:

formatid : function(id){
    mOrders.formatOrderID(id, function(err, formatted_id){
        // err is always null, no need to handle
        console.log(formatted_id);
        return formatted_id;
    });
    return 'some_text';
}

给了我以下 html:

<ul>
    <li>some_text</li>
</ul>

我在这里缺少什么?它不是返回的格式化字符串,因为即使我在回调中返回一个字符串,它也会被忽略。

【问题讨论】:

    标签: javascript node.js express helper handlebars.js


    【解决方案1】:

    问题是您试图从异步函数返回一个值,但把手助手是同步的。在mOrders.formatOrderID() 中传递的回调被执行时,您的辅助函数已经退出(使用值undefined,因为在第一个示例中您没有返回回调之外的任何内容,而在第二个示例中使用'some_text')。

    一种解决方案是使mOrders.formatOrderID 同步(如果可能或可行)或使用类似express-hbs 的库并像这样定义asynchronous helpers

    var hbs = require('express-hbs');
    
    hbs.registerAsyncHelper('formatid', function(id, cb) {
      mOrders.formatOrderID(id, function(err, formatted_id){
        // err is always null, no need to handle
        console.log(formatted_id);
        cb(formatted_id);
      });
    });
    

    【讨论】:

    • 谢谢。这很有意义。我使功能同步。出于某种原因,我认为回调和外部没有返回会使其阻塞。我现在明白了,这很愚蠢;)
    猜你喜欢
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 2015-03-05
    • 2013-12-04
    • 2020-12-16
    • 2020-03-13
    相关资源
    最近更新 更多