[英]Synchronous methods in Meteor/Node
我有一个拼写检查句子的功能:
let spellCheck = input => {
let corrected = [];
input.split(' ').map((word, index, array) => {
G.dictionary.spellSuggestions(word, (err, correct, suggestion, origWord) => {
correct ? corrected[index] = origWord : corrected[index] = suggestion[0];
});
});
// terrible solution
Meteor._sleepForMs(200);
return ['SPELL', input, corrected];
};
这里的问题是,返回的语句会在更正后的数组填充有拼写错误的单词的正确版本之前发生。 我的糟糕解决方案是在return语句之前调用sleep函数,但是我不能依靠它。
我已经研究了使用Meteor.wrapAsync()的选项,但是我不知道在哪种方法上使用它。 我试图(天真)使spellCheck方法异步,但是当然不起作用。
有没有办法使G.dictionary.spellSuggestions方法本身同步?
Meteor.wrapAsync
上的官方Meteor文档说:
包装一个将回调函数作为其最终参数的函数。 包装函数的回调的签名应为function(error,result){}
最后一部分是关键。 回调必须具有确切的签名function (error, result) {}
。 因此,我要做的是为G.dictionary.spellSuggestions
创建一个包装,然后在该包装上使用Meteor.wrapAsync
。 例如:
function spellSuggestions(word, callback) {
G.dictionary.spellSuggestions(word, (err, correct, suggestion, origWord) => {
callback(err, { correct, suggestion, origWord });
});
}
// This function is synchronous
const spellSuggestionsSync = Meteor.wrapAsync(spellSuggestions);
我在这里所做的基本上是将非错误结果打包到一个对象中。 如果您直接调用spellSuggestions
(异步),则可能看起来像这样:
spellSuggestions(word, function (error, result) {
if (!error) {
console.log('Got results:', result.correct, result.suggestion, result.origWord);
}
});
因此,现在在服务器端,您可以同步使用函数:
result = spellSuggestionsSync(word);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.