在node.js代码中实现回调的问题

时间:2013-10-31 07:24:51

标签: javascript node.js express

我有这个node.js函数process(),它应该在被调用时返回一个值。我面临着为我的process()创建回调的问题。只有在从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;

3 个答案:

答案 0 :(得分:1)

尝试以下

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

答案 1 :(得分:1)

因为你的进程方法需要一个回调函数并且不返回一个值,你可以这样调用它:

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

答案 2 :(得分:0)

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

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

};