Node Express Handlebars助手不返回函数的结果
我对这个感到困惑。 如果我在一个句柄帮助器中使用一个函数并返回该函数的结果,则不会返回任何结果。
这是模板:
<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; }); }
然而,尽pipe正确的文本被logging到控制台,结果html是:
<ul> <li></li> </ul>
但是,如果我在formatOrderID()函数结束之后放置了一个返回值,它将返回,所以:
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>
我在这里错过了什么? 这不是返回的格式化的string,因为即使当我在callback中返回一个string它被忽略。
问题是你正试图从一个asynchronous函数返回一个值,但是handlebars助手是同步的。 在mOrders.formatOrderID()
得到执行的时候,你的helper函数已经退出(值undefined
,因为在第一个例子中你没有返回任何东西,而在第二个例子中是'some_text'
)。
一种解决scheme是使mOrders.formatOrderID
同步(如果可能或可行)或使用像express-hbs这样的库并定义如下asynchronous助手 :
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); }); });