Meteor / Node中的同步方法

时间:2016-03-30 21:05:14

标签: javascript node.js meteor

我有一个拼写检查句子的函数:

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方法本身同步?

1 个答案:

答案 0 :(得分:2)

Meteor.wrapAsync上的official Meteor docs说:

  

包装一个以回调函数作为最终参数的函数。包装函数的回调签名应该是function(error,result){}

最后一部分是关键。回调必须具有确切的签名function (error, result) {}。所以我要做的是,为G.dictionary.spellSuggestions创建一个包装器,然后在该包装器上使用Meteor.wrapAsync。 E.g:

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);