[英]Issue with Implementing callback in node.js code
I have this node.js function process() which is supposed to return a value when called. 我有这个node.js函数process(),它应该在调用时返回一个值。 I am facing issue with creating a callback for my process().
我在为我的process()创建回调时遇到问题。 The value should return from process() only after it gets response back from ec2.runInstances(params, function(err, data) call.
该值仅在从ec2.runInstances(params,function(err,data)调用)获得响应后才应从process()返回。
------------- Snippet from app.js (express.js)-------------------- -------------来自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 ----------------------- ------------------------ 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;
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
进程= ec2process
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
});
}):
});
You should move the code which calls the callback into the callback for runInstances: 您应该将调用回调的代码移到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);
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.