【问题标题】:Issue with Implementing callback in node.js code在 node.js 代码中实现回调的问题
【发布时间】:2013-11-11 02:32:01
【问题描述】:

我有这个 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 的代码 sn-p --------------- --------

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;

【问题讨论】:

标签: javascript node.js express


【解决方案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

【讨论】:

    【解决方案2】:

    由于您的流程方法需要一个回调函数并且不返回值,因此您可以这样调用它:

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

    【讨论】:

      【解决方案3】:

      您应该将调用回调的代码移动到 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);
        });
      
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-20
        • 1970-01-01
        • 2015-11-01
        • 2016-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-24
        相关资源
        最近更新 更多