I have a function that gets data from AWS:
main.js
const { GetInstancesByName } = require("./functions");
var operationmode = "getinstances";
if (operationmode == "getinstances") {
let getresult = GetInstancesByName(instance);
console.log("(getinstances log)",getresult);
let resultsent = "yes";
callback(getresult);
}
then this is the functions file (functions.js):
functions.js
const GetInstancesByName = function GetInstancesByName(name) {
let ec2 = new AWS.EC2({apiVersion: '2016-11-15'});
//console.log(ec2);
let params = {
Filters: [
{
Name: "tag:Name",
Values: [
name
]
}
]
};
ec2.describeInstances(params, function(err, data) {
if (err)
console.log("error",err, err.stack); // an error occurred
else return data; // successful response
/*
data = {
}
*/
});
return data;
};
I am trying to get the data from the (error , data) in the function. I have tried: setting a var/const/let to the data. the return data at the bottom works but data is empty. I want to get data so I can pass it back in the GetInstancesByName (being used by main.js).
on the main both console.log("(getinstances log)",getresult) and callback(getresult); both return not defined.
Any help would be much appreciated.
Thank You
If you don't want to use async/await, you may pass a callback to GetInstancesByName as follows:
function GetInstancesByName (name, callback) {
// ...
ec2.describeInstances(params, function(err, data) {
if (err) {
console.log("error",err, err.stack); // an error occurred
} else {
callback(data); // successful response
}
});
// ...
}
// In main.js
GetInstancesByName(instance, data => {
// do something with data
});