I awaited my function at many places but it still showing promise pending.
I am trying to get YouTube video thumbnails by url.
I created a index.js file with this code:
const checkurl = require('./checkurl.js');
console.log(checkurl('https://youtu.be/NbT4NcLkly8'));
and the checkurl.js have:
const getvideoid = require('get-video-id');
const https = require('https');
const GOOGLEKEY = process.env['GOOGLEKEY'];
module.exports = async function(url) {
const urlinfo = getvideoid(url)
if (urlinfo.service == 'youtube' && urlinfo.id !== undefined) {
const result = await checkid(urlinfo.id)
return result
}
return false
};
function checkid(id) {
return new Promise((resolve, reject) => {
const url = 'https://www.googleapis.com/youtube/v3/videos?key=' GOOGLEKEY '&part=snippet&id=' id
const req = https.request(url, (res) => {
res.setEncoding('utf8');
let responseBody = '';
res.on('data', (chunk) => {
responseBody = chunk;
});
res.on('end', () => {
const data = JSON.parse(responseBody);
if (data.items[0]) {
const thumbnail = data.items[0].snippet.thumbnails
resolve(thumbnail);
} else {
resolve(undefined);
};
});
});
req.on('error', (err) => {
reject(err);
});
req.end();
});
};
I awaited all my function which return promise but I am still getting promise pending idk why.
I also tried to resolve the promise in second function but still same.
CodePudding user response:
checkurl
returns a Promise
because it's an async
function.
You either need to await
or .then
it before you can console.log
its value.
// in an async function
console.log(await checkurl('https://youtu.be/NbT4NcLkly8'));
checkurl('https://youtu.be/NbT4NcLkly8').then(console.log)