Reputation: 3501
I am working on my first node module and I am struggling a little bit with variables in my functions. The first console log gives me my data, but the second console log is giving me undefined.
module.exports = {
getClient: function() {
var options_auth={user: username, password: password};
return new Client(options_auth);
},
getTestCaseById: function(client, args, testCaseId) {
var restResponse;
url = baseurl + "testcase/" +testCaseId;
client.get(baseurl + "testcase/" +testCaseId, args, function(data, response) {
restResponse = data;
console.log(data);
});
console.log(restResponse);
}
};
Thoughts on what I am doing wrong with that restResponse variable.
Upvotes: 1
Views: 102
Reputation: 104795
That's because the .get
call is async. The console.log after the client.get
function is ran while that data call is still in progress. The one inside that call is ran once the call is complete - called a callback function.
Do all of your work within the callback to use the returned data, or pass the returned data to another function.
To return the data:
getTestCaseById: function(client, args, testCaseId, callback) {
var restResponse;
url = baseurl + "testcase/" +testCaseId;
client.get(baseurl + "testcase/" +testCaseId, args, function(data, response) {
restResponse = data;
callback(data)
});
}
Then pass a callback in:
getTestCaseById(client, args, testCaseId, function(response) {
console.log(response); //your returned data
});
Upvotes: 1