Node Express Handlebars 助手不返回函数结果
Node Express Handlebars helper not returning result of function
我对此感到困惑。如果我在 handlebars helper 中使用一个函数并且 return 该函数的结果,则没有任何内容被 returned.
这是模板:
<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,它会得到 returned,因此:
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>
我在这里错过了什么?它不是 returned 格式化字符串,因为即使我 return 回调中的字符串也会被忽略。
问题是您正在尝试 return 来自异步函数的值,但 handlebars 助手是同步的。当传入 mOrders.formatOrderID()
的回调被执行时,您的辅助函数已经退出(值为 undefined
,因为您在第一个示例中没有 return 回调之外的任何内容,并且 'some_text'
在你的第二个例子中)。
一个解决方案是使 mOrders.formatOrderID
同步(如果可能或可行)或使用像 express-hbs and define 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);
});
});
我对此感到困惑。如果我在 handlebars helper 中使用一个函数并且 return 该函数的结果,则没有任何内容被 returned.
这是模板:
<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,它会得到 returned,因此:
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>
我在这里错过了什么?它不是 returned 格式化字符串,因为即使我 return 回调中的字符串也会被忽略。
问题是您正在尝试 return 来自异步函数的值,但 handlebars 助手是同步的。当传入 mOrders.formatOrderID()
的回调被执行时,您的辅助函数已经退出(值为 undefined
,因为您在第一个示例中没有 return 回调之外的任何内容,并且 'some_text'
在你的第二个例子中)。
一个解决方案是使 mOrders.formatOrderID
同步(如果可能或可行)或使用像 express-hbs and define 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);
});
});