I'm making a discord bot to play youtube video. I'm using this google API to get the video titles from their IDs but the get_title() function returns an empty jsons array.
I've tried to log the jsons array right after the request() function and right after the map() function but they both return empty arrays. If i console.log(jsons) right after jsons.push(json) , it does return arrays with titles.
const browser = require('https')
var urls = ['https://www.googleapis.com/youtube/v3/videos?key=AIzaSyC7udvST-lyLpx_gxHBc22kGYhEUOeQz5k&part=snippet&id=QKm4q6kZK7E', 'https://www.googleapis.com/youtube/v3/videos?key=AIzaSyC7udvST-lyLpx_gxHBc22kGYhEUOeQz5k&part=snippet&id=ib3fDx75Esw']
function get_title() {
return new Promise(function(resolve, reject) {
var jsons = []
urls.map(url => {
browser.request(url, res => {
let body = ''
res.on('data', data => {
body += data
})
res.on('end', () => {
var json = JSON.parse(body).items[0].snippet.title
jsons.push(json)
})
}).end()
})
resolve(jsons)
})
}
async function main() {
res = await get_title()
console.log(res)
}
main()
I expect the output to be like this
[ 'Santa Tracker: Making a penguin-proof password','Google Duo: Stay in touch after the Holidays' ]
jsonsbefore you receive any response for your API calls. The data is pushed to jsons, but the result has already been returned.