I'm new to Node JS and I can't seem to figure out why i'm getting an 'undefined' when using an async function. I've wrapped the async function in a promise and it resolves after an API request has been completed.
let req = (url) => new Promise((resolve, reject) => {
var options = {
'method': 'GET',
'url': url,
'headers': {
'Content-Type': 'application/json'
}
}
request(options, function (error, response) {
if (error) {
reject(error)
} else {
resolve(response.body)
}
})
})
.then((results) => {
//console.log(results) //this shows the results when uncommented!
console.log('request has been completed')
})
.catch((error) => {
console.log(error)
})
Here is the function that triggers the 'req' function and then says 'undefined' when I log the value:
let getAllData = async (url) => {
var endpoint = `${url}?apikey=${settings.api_key}`
let res = await req(endpoint)
console.log('run after request') //successfully runs after request is resolved above
console.log(res) //gives me 'undefined'
}
Here is my output.
request has been completed
run after request
undefined
What am I doing wrong here?