通过使用回调全局访问node js中的变量


Access variable globally in node js by using callbacks

是否有任何方法可以使用callbacks访问函数外的结果或全局使用结果。例如,

execPhp('sample_php.php', function(error, php, outprint){ 
  php.decode_key(fromUserId, function(err, fromId, output, printed){});
});

在这里,我需要获得php.decode_key外部的输出值。有人能帮忙找到解决方案吗?

Ideea是不能在回调之外使用fromId,它是异步计算的(这段代码正在生成一个child-process,他在其他执行线程中与主代码并行运行它。)PHP开发人员在运行到节点时使用的一个常见示例如下:

var globalVar;
execPhp('sample_php.php', function(error, php, outprint){ 
   php.decode_key(fromUserId, function(err, fromId, output, printed){ 
      globalVar = fromId;
   });
});

不起作用,因为所有的async方法都是在并行单元中运行的,它们不共享上下文(这是javascript的异步范式,并发模型)),所以从这个意义上说,你可以做的是在php.decode_key方法的回调中编写代码。

一个更干净的方法可以是具体化一个模块keydecoder.js,并在您的主要项目中异步使用它:

//keydecoder.js
var execPhp = requiere('exec-php');
module.exports = function(fromUserId, cb) {
  execPhp('sample_php.php', function(error, php, outprint) {
    if (error) {
      cb(error);
    } else {
      php.decode_key(fromUserId, function(err, fromId, output, printed) {
        cb(err, fromId);
      });
    }
  });
};

你可以这样使用它:

var keyDecoder = require('../modules/keydecoder');
keyDecoder(fromUserId, function(err, result) {
   //use in main code
});