1

我有这个 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;
4

3 回答 3

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

});


};

出口。进程 = ec2process

于 2013-10-31T07:29:35.977 回答
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
        });
    }):  
});
于 2013-10-31T07:29:51.663 回答
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);
  });

};
于 2013-10-31T07:28:47.497 回答