php - 使用回调在 Node js 中全局访问变量

标签 php node.js callback

有没有办法使用回调来访问函数外部的结果或全局使用结果。 例如,

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

这里我需要在 php.decode_key 之外获取 output 值。 任何人都可以帮助找到解决方案吗?

最佳答案

想法是你不能在回调之外使用fromId,它是异步计算的(此代码正在生成一个子进程,并且他在其他执行线程中与主代码并行运行它。) PHP 开发人员在遇到 Node 时的一个常见使用示例如下:

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
});

关于php - 使用回调在 Node js 中全局访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36332901/

相关文章:

php - 使用 phpword 设置全局段落样式

javascript - Angular $http POST 无法将数据发送到expressjs

javascript - 将外部 JavaScript 库转换为 Node.js 模块

node.js - 如何知道何时完成

Python C API - 从嵌入式 python 调用 C 函数(回调)

JavaScript:带有回调和参数的事件监听器

php - 在 PHP 中执行 javascript

php - 在php中为给定时间添加时区

php - 使用 PHP 向 Urban 飞艇发送消息

c++ - C++03 中的 <functional> 函数对象有什么用处?