将asynchronous函数转换为同步函数

我使用某个Node.js类来进行文本分类。 最简单的forms如下所示:

function TextCategorizer(preprocessors) { ... } 

“预处理器”是一种forms的函数的数组:

 function(text) { return "<modified text>" } 

例如,它们可以用于删除标点符号,转换为小写字母等。

我可以像这样使用TextCategorizer:

 var cat = newTextCategorizer(preprocessors); cat.train(text1,class1); cat.train(text2,class2); ... console.log(cat.classify(text3,class3); 

预处理器被调用以便为每个训练文本和分类文本。

现在,我需要添加一个新的预处理函数 – 一个拼写纠正器。 最好的拼写纠正,我发现asynchronous(通过networking服务),所以,function看起来像这样:

 correctSpelling(text, callback) { ... callback(corrected_version_of_text); } 

即它不返回一个值,而是用该值调用一个callback函数。

我的问题是:我怎样才能使用correctSpelling函数,作为我发送到TextCategorizer的预处理器数组中的预处理器之一?

如果你想以一定的顺序放置一堆任务,你可以使用asynchronous框架(npm install async)。 同步asynchronous函数称为“系列”有一个特定的function。

这听起来像使用同步和asynchronousfunction有问题。 在这种情况下,我认为你应该把所有的同步函数包装在一个asynchronous函数中

 function asyncFunc(args, callback){ process.nextTick(function() { callback(syncFunc(args)); }); } 

那么你应该使用async模块链接在一起。

看起来这可能会使asynchronous函数同步。

waitfor在github上

如果我上面关于我的理解你的问题的评论是正确的,我不认为有一种方法可以按照你想要的方式去asynchronous调用一个asynchronous调用,而不需要修改TextCategorizer的源代码,是最佳的。

我唯一的想法是在调用train()和classify()之前,通过现有的预处理器列表来运行你的文档,这将允许你遵循JoshC的build议。

如果你真的想要这样做,你可以试试Fibers

 var Future = require('fibers/future'), wait = Future.wait; var fs = require('fs'); // This wraps existing functions assuming the last argument of the passed // function is a callback. The new functions created immediately return a // future and the future will resolve when the callback is called (which // happens behind the scenes). var readdir = Future.wrap(fs.readdir); var stat = Future.wrap(fs.stat); Fiber(function() { // Get a list of files in the directory var fileNames = readdir('.').wait(); console.log('Found '+ fileNames.length+ ' files'); // Stat each file var stats = []; for (var ii = 0; ii < fileNames.length; ++ii) { stats.push(stat(fileNames[ii])); } wait(stats); // Print file size for (var ii = 0; ii < fileNames.length; ++ii) { console.log(fileNames[ii]+ ': '+ stats[ii].get().size); } }).run(); 

参见FUTUREShttps://github.com/laverdet/node-fibers#futures