asked on
I'm using https.get() to fetch an api, however to use async await I'm trying to promisify the function. While I can retrieve the data, if I try to do anything to access the data or loop through the object, or access anything in the object, it will read ``'Cannot read property '0' of undefined'. However, if I try to resolve the data with 'newdata[0]' as shown below, it will return with just `Promise { <pending> }.
Why am I not able to get asynchronous operation I'm trying for below? Or is there a better way to do this? Basically I'm just trying to make an asynchronous operation with async await, and I need to use https (not fetch, axios, etc).
```````
const https = require('https');
const myfunc = ((url) => {
return new Promise((resolve, reject) => {
https.get(url, res => {
let data = [];
res.on('data', chunk => {
data.push(chunk);
});
res.on('end', () => {
let newdata = JSON.parse(Buffer.concat(data).toString())
resolve(newdata[0]);
});
}).on('error', err => {
console.log('Error: ', err.message);
});
});
});
async function getApi() {
let url = [redacted url];
await myfunc(url)
.then(data => {
console.log(data)
})
.catch(err => {
console.log(err)
});
}