2016-03-31 26 views
1

有什麼方法可以使用callbacks來訪問函數外的結果或全局使用結果。 例如,使用回調函數在節點js中全局訪問變量

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

在這裏,我需要得到外界php.decode_key輸出值。 任何人都可以幫助找到解決方案嗎?

+0

而且什麼問題,似乎你正在使用'php-exec'模塊,但我沒有看到這個東西不應該工作,你會得到任何錯誤? –

+0

它可以很好地工作,但我需要php.decode_key之外的輸出(來自UserId,函數(err,fromId,output,printed){ }); –

回答

0

的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的的asyncrhonous範式, ),所以你可以在這個意義上做什麼,就是把你的代碼編寫成php.decode_key方法的回調OD。

一個清潔的方式可以是克里特模塊keydecoder.js,並在您的主項目asynchornously使用它:

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