我对此感到困惑。如果我在一个手把助手中使用一个函数并返回该函数的结果,则不会返回任何结果。
这是模板:
<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()函数结束后放了一个返回,它就会被返回,所以这个:
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>
我在这里错过了什么?它不是返回的格式化字符串,因为即使我在回调中返回字符串,它也会被忽略。
问题是您试图从异步函数返回一个值,但handlerbars助手是同步的。当mOrders.formatOrderID()
中传递的回调被执行时,您的助手函数已经退出(值为undefined
,因为在第一个示例中您没有返回回调之外的任何内容,在第二个示例中使用'some_text'
)。
一种解决方案是使mOrders.formatOrderID
是同步的(如果可能或可行的话),或者使用类似express hbs的库,并定义这样的异步助手:
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);
});
});