Randeep
Randeep

Reputation: 99

Issue with Implementing callback in node.js code

I have this node.js function process() which is supposed to return a value when called. I am facing issue with creating a callback for my process(). The value should return from process() only after it gets response back from ec2.runInstances(params, function(err, data) call.

------------- Snippet from app.js (express.js)--------------------

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

});

------------------------Code snippet from 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;

Upvotes: 1

Views: 117

Answers (3)

gherkins
gherkins

Reputation: 14973

since your process method expects a callback function and does not return a value, you could call it rather like this:

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

Upvotes: 1

HILARUDEEN S ALLAUDEEN
HILARUDEEN S ALLAUDEEN

Reputation: 1752

Try as follows

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

});


};

exports. process = ec2process

Upvotes: 1

Brett
Brett

Reputation: 3885

You should move the code which calls the callback into the callback for 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);
  });

};

Upvotes: 0

Related Questions