将异步函数转换为同步函数 [英] Convert an asynchronous function to a synchronous function

查看:114
本文介绍了将异步函数转换为同步函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用某个Node.js类进行文本分类.最简单的形式如下:

I use a certain Node.js class for text categorization. In its simplest form, it looks like this:

function TextCategorizer(preprocessors) {
      ...
}

预处理器"是以下形式的函数数组:

"preprocessors" is an array of functions of the form:

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

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

They can be used, for example, to remove punctuations, convert to lower case, etc.

我可以像这样使用TextCategorizer:

I can use the TextCategorizer like this:

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

为每个训练文本和分类文本依次调用预处理器.

The preprocessors are called in order for every training text and classified text.

现在,我需要添加一个新的预处理器功能-拼写校正器.我发现的最正确的拼写纠正方法(通过Web服务)异步工作,因此,该函数如下所示:

Now, I need to add a new preprocessor function - a spelling correcter. The best spelling corrected I found works asynchronously (through a web-service), so, the function looks like this:

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

即它不返回值,而是使用该值调用回调函数.

i.e. it does not return a value, but rather calls a callback function with the value.

我的问题是:作为发送到TextCategorizer的预处理器数组中的预处理器之一,我该如何使用正确的拼写功能?

My question is: how can I use the correctSpelling function, as one of the preprocessors in the preprocessors array I send to TextCategorizer?

推荐答案

如果要按特定顺序放置一堆任务,可以

If you want to put a bunch of tasks in a certain order, you could you the async framework (npm install async). There is a specific feature for synchronizing async functions called "series".

听起来您在使用同步和异步功能时都遇到问题.在这种情况下,我认为您应该将所有同步功能都包装在这样的异步功能中

It sounds like you are having a problem using both sync and async functions. In that case, I think you should wrap all sync functions in an async function like so

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

然后,您应该使用 async 模块将它们链接在一起.

Then you should chain them together using the async module.

看起来这可能会使异步函数同步.

It looks like this may make an asynchronous function synchronous.

在github上等待

这篇关于将异步函数转换为同步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆