有没有办法使用回调
来访问函数外部的结果或全局使用结果。
例如,
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/