2013-08-22 108 views
1

我使用某个Node.js类进行文本分类。在最简单的形式,它看起来像这样:将异步函数转换为同步函数

function TextCategorizer(preprocessors) { 
     ... 
} 

“预处理程序”是形式的函数数组:

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

他们可以使用,例如,以去除标点符号,转换成下壳体等

我可以使用TextCategorizer这样的:

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

的preproces为了每个训练文本和分类文本,都会调用sors。

现在,我需要添加一个新的预处理器函数 - 拼写纠正器。最好的拼写纠正我发现作品异步(通过Web服务),因此,功能如下:

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

即它不返回值,而是要求与价值的回调函数。

我的问题是:我如何使用correctSpelling函数作为预发送器阵列中的一个预处理器发送给TextCategorizer?

+0

为什么不异步使用它呢?异步是节点口头禅。 –

+0

作为一个独立的函数,我当然可以异步使用它。但正如我在问题中所解释的那样,我想用它作为另一个模块的输入,它需要一个同步功能。 –

+0

使用异步调用将预处理程序放入关闭中。然后在这个闭包中定义你的回调,所以回调函数可以访问预处理器数组。 – ChrisCM

回答

2

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

听起来好像您在使用同步和异步功能时遇到了问题。在这种情况下,我认为你应该换了所有的同步功能,在异步函数像这样

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

那么你应该使用async模块把它们结合在一起。

它看起来像这可能使异步函数的同步。

waitfor on github

+0

“系列”采用一组异步函数,按顺序调用它们,并将结果返回给另一个回调函数。但是,我仍然没有看到如何使用它来向需要同步函数的类发送异步函数... –

+0

@ErelSegalHalevi能否包含更多代码?我不明白为什么你可以异步传递同步回调到你的函数。 –

+0

你对TextCategorizer有什么访问权限?如果您可以访问源代码,我相信您可以使用基于事件的解决方案(我将根据您的回答进行描述)。 –

1

如果以上关于我对你的问题的理解我的意见是正确的,我不相信有一种方式未asynchronizing一个异步调用你想要的方式,无需修改TextCategorizer源,你表示不会是最佳的。

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

1

如果你真的想要这样做,你可以试试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(); 

期货https://github.com/laverdet/node-fibers#futures