简体   繁体   English

翻译工具的javascript回调

[英]javascript callbacks for translation tool

I'm trying to build a translation engine using node.js. 我正在尝试使用node.js构建翻译引擎。 I have a Python/R background so I'm not getting the hang of these so called callbacks . 我有Python / R背景知识,所以我对这些所谓的callbacks没什么了解。 . .

The input is a sentence : 输入的是一个句子:

 var sentence = "I want to translate this"

When I hit the "Translate" button, it should trigger the translation. 当我点击“翻译”按钮时,它应该触发翻译。

Now this is the database query, I call a node.js backend at /translate 现在这是数据库查询,我在/ translate调用一个node.js后端

function query(string){
   var query = 
   db.call.get(query, function(result){
       if(result.length>0){
           console.log(result[0].translation);
       } else {
           // not found in database
           console.log(string);
       }
   });
}

So then it goes like this: 因此,它像这样:

var wordList = sentence.split(" ");
for(i=0; i<wordList.length; i++){
     // i call the database to return me the translation for each word
     query(wordList[i]);
}

But then, the output in the console log comes like this: 但是,控制台日志中的输出如下所示:

output[0]: "translate", "want", "to", "I"

How can I make it come back in order? 我怎样才能使它恢复原状? I understand there is some async and callback stuff going on, but I do believe that the guys who coded node are smart and that there is surely a way to solve this pretty easily. 我知道发生了一些异步和回调事件,但是我确实相信对节点进行编码的家伙很聪明,并且肯定有一种很容易解决此问题的方法。 Thanks 谢谢

You need to take into account the fact that your query function might take a different time to return depending on the string argument you pass it. 您需要考虑以下事实:查询函数可能需要不同的时间才能返回,具体取决于传递给它的字符串参数。 Right now, in your example code, if the query for "want" returns before the query for "I", then your translations will be outputted in the same order that the queries return (ie translation of "want", translation of "I"). 现在,在您的示例代码中,如果对“ want”的查询在对“ I”的查询之前返回,那么您的翻译将以查询返回的相同顺序输出(即,“ want”的翻译,对“ I”的翻译”)。

Callbacks can help you get around this problem, because they are a function that will only get called when your query function returns. 回调可以帮助您解决此问题,因为它们是仅在查询函数返回时才被调用的函数。 Then it's up to you to define what your program should do with the result. 然后由您决定程序应如何处理结果。 For instance, your program can output the results in the same order that the original array was in. This could be achieved using an index as suggested by Guffa, or using the async library that we will discuss later on. 例如,您的程序可以按照与原始数组相同的顺序输出结果。这可以通过使用Guffa建议的索引或使用稍后将讨论的异步库来实现。

So, one thing you could try is to pass query a callback like this: 因此,您可以尝试的一件事是传递查询这样的回调:

function query(string, callback){
   db.call.get(query, function(result){
       if(result.length>0){
           callback(null, result[0].translation);
       } else {
           // not found in database
           callback(null, string);
       }
   });
}

The canonical way to use callbacks in Node.js, is to give it two parameters, so it looks like: callback(err, result) . 在Node.js中使用回调的规范方法是为其提供两个参数,因此看起来像: callback(err, result) If there is no error, you can call callback(null, result) , while when there is an error, you can call callback(err) or callback (err, result) , depending on what you want to report. 如果没有错误,则可以调用callback(null, result) ,而在发生错误时,可以根据要报告的内容调用callback(err)callback (err, result)

Once your query function takes a callback, you are able to know when it did return a value, and you can use the async.map function (from the async library ), like so: 查询函数接受回调后,您就可以知道它何时返回值,并且可以使用async.map函数(来自async库 ),如下所示:

var async = require('async');
var sentence = "I want to translate this";
var words = sentence.split(' ');

async.map(words, query, function (err, translations) {
   console.log(translations);
}

What this function does, is: 该函数的作用是:

  • run in parallel query on all the items in the words array 在word数组中的所有项目上并行查询
  • wait for all the callbacks from all the query functions to return 等待所有查询函数的所有回调返回
  • then call async.map 's own callback (here the third argument: function (err, translations) {console.log(translations);} ) 然后调用async.map自己的回调(此处为第三个参数: function (err, translations) {console.log(translations);} )))

The only way to make them come back in order would be to chain the calls, but then you take away the point of having asynchronous calls in the first place. 使它们按顺序返回的唯一方法是将调用链接起来,但是首先您就不用进行异步调用了。

Send along the index for the word also, that way you can put the results together in the right order: 还发送单词的索引,这样您就可以按正确的顺序将结果放在一起:

var wordList = sentence.split(" ");
var resultList = [];
var resultCount = 0;
for (i = 0; i < wordList.length; i++){
  // i call the database to return me the translation for each word
  query(wordList[i], i);
}

function query(string, index){
  var query = db.call.get(query, function(result){
    if (result.length > 0){
      resultList[index] = result[0].translation;
    } else {
      // not found in database
      resultList[index] = string;
    }
    resultCount++;
    if (resultCount == wordList.length) {
      console.log(resultList);
    }
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM