node.js中的同步行为

时间:2012-10-04 01:14:01

标签: node.js synchronous

所以...我知道这不是正确的方式...但我有一个我自己进入的盒子,如果我能找到一种方法,我看起来最容易导航“get”请求在node.js

中同步运行

是的,我尝试了节点同步(看起来应该可以正常工作)

情景就是这个

  • 从文件中读取参数化字符串(已完成,工作正常)
  • 递归地对字符串进行标记,将其分解为键和字符串。价值(完成,工作正常)
  • 拨打Google翻译来翻译每个值(休息!)
  • 重新组装参数化字符串并将其写回输出文件(完成,工作正常)

我知道如何调用google translate(可以很容易地对整个字符串进行调用),但无法理解如何获得异步回调的排序与参数化字符串上的递归一致我拥有的数据集是必要的。

如果我可以将对Web服务的调用表现为同步,那么这将很简单。 e.g。

read string (while not EOF)
    recurse (get the next token)
        translate the fragment (which is done with request.get()
        add translated fragment to the current string
    assemble translated string
    write to file

节点同步示例有效,但我无法使用request.get()

有什么建议吗?

摘录

// this function gets passed in a string and recursively pulls out and
// attempts to translate tokens.  It needs to do this as the data source
// contains "key" = "fragment" + $(paramter1) + fragment + $(parameter2) etc

function getTokenSegment(sourceString){

s = sourceString;  //lazy

// if the string contains a parameter 
if (s.indexOf(leadingDelimiter) != -1) {    

    // extract the tokens...omitted the error checking (which all works)
    translatedToken = syncTranslate(token);   // <--- THIS IS WHAT I WANT...
    parameter = s.substring(token.length+1, s.indexOf(trailingDelimiter)+1);
    remainder = s.substring(token.length + parameter.length+1, s.length);

    translatedString = translatedString + translatedToken + parameter 

        // recursive call to get the rest of the string
        + getTokenSegment(remainder);
}
else {  

    // the remainder of the string can be translated intact
    translatedToken = syncTranslate(s);
    translatedString = translatedString + translatedToken;
}
return (translatedString);
}

function syncTranslate(stringToTranslate) {
    var sync = require('sync');
sync(function(){
    var result = translate.sync(null, {key: key, q: stringToTranslate, target: language});
})
    return result;  
}


// translate module is from Mike Holly -- https://github.com/mikejholly/node-google-translate
// and worked perfectly when I used it on non-parameterized strings.  only edit is the NULL as the
// first parameter in the callback, copied from the node-sync simple example]


var request = require('request')
  , _ = require('underscore')
  , querystring = require('querystring')
  , util = require('util')

module.exports = function(opts, callback) {

// parse & default the arguments
opts = _.defaults(opts, {
    source: 'en',
    target: 'fr',
    key: 'secret', 
    sourceText: 'text'
});

var url = 'https://www.googleapis.com/language/translate/v2?' + querystring.stringify(opts);

request.get(url, function(err, response, body){

   if (err) throw err;

   // parse the returned JSON
       var json = JSON.parse(body);
       if (json.error) {
          throw json.error.message;
    }
    var strings = util.isArray(opts.sourceText) ? opts.sourceText : [opts.sourceText];

    var result = {};
var translatedString = '';
    strings.forEach(function(original, i){
      result[original] = json.data.translations[i].translatedText;
  translatedString = result[original];

   });

   callback(null, translatedString);

   });

};

2 个答案:

答案 0 :(得分:0)

我猜这里,因为你的问题不够明确。我很感激你的困难,因为很难谈论软件。我想您忘了将代码包装在同步块中:

// Run in a fiber
Sync(function(){

    // your code

})

来源:https://github.com/0ctave/node-sync#examples

我给你一个提示。首先尝试最简单的任务。尝试翻译只有一个单词,然后使用翻译后的单词。在request.get()内使用Sync执行此操作。当这种方法有效时,您会更加信任该软件,并且更有信心继续处理更复杂的事情。

答案 1 :(得分:0)

在node.js中编写同步代码的一个非常流行的模块是async。对于您的问题,我会尝试waterfall函数:

async.waterfall([
    // your first function
    function(callback){
        callback(null, 'one', 'two');
    },
    // your second function
    function(arg1, arg2, callback){
        callback(null, 'three');
    },
    // your third function
    function(arg1, callback){
        // arg1 now equals 'three'
        callback(null, 'done');
    }
], function (err, result) {
   // result now equals 'done'    
});
相关问题