Javascript Meteor/Node中的同步方法

Javascript Meteor/Node中的同步方法,javascript,node.js,meteor,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[inde

我有一个检查句子拼写的功能:

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语句发生在更正的数组中填充有拼写错误的单词的正确版本之前。我糟糕的解决方案是在return语句之前只调用一个sleep函数,但我不能依赖它

我已经研究过使用Meteor.wrapAsync()的选项,但是我不知道在哪个方法上使用它。我尝试(天真地)使拼写检查方法异步,但当然没有成功


有没有办法使G.dictionary.spellSuggestions方法本身同步?

Meteor.wrapAsync上的

包装将回调函数作为其最终参数的函数。包装函数的回调的签名应该是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(word, function (error, result) {
  if (!error) {
    console.log('Got results:', result.correct, result.suggestion, result.origWord);
  }
});
因此,现在在服务器端,您可以同步使用您的功能:

result = spellSuggestionsSync(word);
Meteor.wrapAsync上的

包装将回调函数作为其最终参数的函数。包装函数的回调的签名应该是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(word, function (error, result) {
  if (!error) {
    console.log('Got results:', result.correct, result.suggestion, result.origWord);
  }
});
因此,现在在服务器端,您可以同步使用您的功能:

result = spellSuggestionsSync(word);

拼写建议是一个异步函数。唯一的解决方案是将拼写检查设为异步函数。不要使用sleep@thangngoc89这将如何解决我的问题?这同样适用,因为即使拼写检查函数异步运行,更正后的列表仍将为空。这里所说的
async
是指回调、承诺或async/wait.G.dictionary.spellSuggestions是一个异步函数。唯一的解决方案是将拼写检查设为异步函数。不要使用sleep@thangngoc89这将如何解决我的问题?这同样适用,因为即使拼写检查函数异步运行,更正后的列表仍将为空。这里所说的
async
是指回调、承诺或异步/等待。这对我不起作用。我收到一条错误消息说err没有定义?我希望这个方法的文档中有一些Meteor文档的例子。这对我来说不起作用。我收到一条错误消息说err没有定义?我希望这个方法的文档中有一些Meteor文档的例子。