im doing some online test , which i need to call a function , inside that function send an http request to an api and return its response
function callapi()
{
require('https').get(`https://example.com/api/getdata`, (res) =>
{
res.setEncoding('utf8');
res.on('data', function (body)
{
var data = JSON.parse(body);
return(data);
});
});
}
sine the call is async i need to wrap it inside a promise so the function would return after reciving response
function callapi()
{
return new Promise(function (resolve, reject)
{
require('https').get(`https://example.com/api/getdata`, (res) =>
{
res.setEncoding('utf8');
res.on('data', function (body)
{
var data = JSON.parse(body);
resolve(data);
});
});
})
}
here is the problem , since resolve response is not readable if i console.log it i get
console.log(callapi());
Promise { <pending> }
i need to call it like
callapi.then(function (result)
{
console.log(result)
})
so i can have a readable data , but the test doesn't allow me to change its structure and requires my function to return the data without needing to use .then
to see the result ... so my question is how can return the data from function without needing to using .then
to see the output
** ps : i dont have to use promise , any other solution will work **