As your request function is async operation, your function returns even before the callback of request is called, you can use of the following approaches.
1. Callback Approach: Make getData function a callback function, and call the callback once you get response in the body.
// Definition
function getData (jsonData, cb){
request(jsonData, function(error, response, body){
if(body){
return cb(null, JSON.parse(body));
}
return cb(error);
});
}
// Invocation
getData({}, function(error, response) {
if (error){
console.log(error);
return;
}
console.log(response);
})
2. Promises Approach: Promises is a nice way to deal with async functions. Wrap your function inside a promise. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
// Definition
function getData (jsonData){
return new Promise((resolve, reject) => {
request(jsonData, function(error, response, body){
if(body){
return resolve(JSON.parse(body));
}
return reject(error);
});
});
}
// Invocation
getData({})
.then(response => console.log(response))
.error(error => console.log(error));
3. Async Await Approach: This is the new way of writing async functions in a synchronous way. For this nothing changes on the definition like promises as request uses callback.
// Definition
function getData (jsonData){
return new Promise((resolve, reject) => {
request(jsonData, function(error, response, body){
if(body){
return resolve(JSON.parse(body));
}
return reject(error);
});
});
}
// Invocation if calling outside
(async() => {
try {
const response = await getJsonData({});
console.log(response);
} catch (err) {
console.log(err);
}
})();
// in another function
async function test() {
const response = await getJsonData({});
console.log(response);
}