问题在Node.js代码中实现callback

我有这个node.js函数process()应该返回一个值时被调用。 我正在为我的过程()创build一个callback的问题。 只有在从ec2.runInstances(params,function(err,data)调用获得响应后,该值才会从process()返回。

————-从app.js(express.js)的片段——————–

var createEngine = require('./ec2_create.js'); app.get('/create', function (req, res) { res.render('create', { status: createEngine.process() }); }); 

————————来自ec2_create.js的代码片段——————– —

 function process(callback) { var status = null; // Create the instance ec2.runInstances(params, function (err, data) { if (err) { //console.log("Could not create instance", err); status = "Could not create instance: " + err; } else { var instanceId = data.Instances[0].InstanceId; //console.log("Created instance", instanceId); status = "Created instance: " + instanceId; } }); callback(status); }; module.exports.process = process; 

尝试如下

 function ec2process(callback){ var status = null; // Create the instance ec2.runInstances(params, function(err, data) { if (err) { //console.log("Could not create instance", err); status = "Could not create instance: " + err; } else{ var instanceId = data.Instances[0].InstanceId; //console.log("Created instance", instanceId); status = "Created instance: " + instanceId; } callback(status); // Callback moved }); }; 

出口。 process = ec2process

由于你的过程方法需要一个callback函数,并且不返回一个值,所以你可以这样调用它:

 app.get('/create', function (req, res) { createEngine.process(function(status){ //you're inside the callback and therefor have the status value res.render('create', { status: status }); }): }); 

您应该将调用callback的代码移动到runInstances的callback中:

 function process(callback) { var status = null; // Create the instance ec2.runInstances(params, function (err, data) { if (err) { //console.log("Could not create instance", err); status = "Could not create instance: " + err; } else { var instanceId = data.Instances[0].InstanceId; //console.log("Created instance", instanceId); status = "Created instance: " + instanceId; } callback(status); }); };