Jonáš Jančařík
2 min readFeb 21, 2020

--

I think the main problem is (probably) that you are returning a promise from within a function which you call (recursively) from within the setTimeout callback, meaning the promise never makes it to the abc function.

When you checkAvailability(options) from within the setTimeout, it returns a promise, but that promise doesn’t go further up (because you don’t do anything with the returned value from the function when you call it for the second or third time).

I would probably go about this differently anyway, but I think that’s where your main problem with the unhandled promise rejection is.

I hope this helps.

Edit: I had a look at it and here is roughly how I would do it:

let https = require('https');
const CONST = {
MEDIA_NAME: 'twitter',
CHAR_LIMIT: 256,
SKIPPABLE_ERR_CODES: [
187, // Status is a duplicate
324, // Uploaded media issue with size/validation
],
DOWNLOAD_ATTEMPT_LIMIT: 3,
AVAILABILITY_ATTEMPT_LIMIT: 3,
MEDIA_AVAILABLE: false,
ATTEMPTS: 0
};
async function checkAvailability(options) {
return new Promise(async (success, failure) => {
while (!CONST.MEDIA_AVAILABLE || CONST.ATTEMPTS < CONST.AVAILABILITY_ATTEMPT_LIMIT) {
function httpsRequest(params) {
return new Promise(function (resolve, reject) {
console.log('attempting...')
let req = https.request(params)
req.on('response', (res) => {
if (res.statusCode == 200) {
console.log('found')
CONST.MEDIA_AVAILABLE = true;
resolve('success')
} else {
console.log('attempting again')
reject(res.statusCode)
}
})
req.on('error', (e) => {
reject(`problem with request: ${e.message}`)
});
req.end()
})
}
try {
CONST.ATTEMPTS++
var req = await httpsRequest(options)
} catch (e) {
console.log(e)
}
if (req === 'success') {
success('success')
return
// return is not strictly necessary since the MEDIA_AVAILABLE is now true
// and the rest of the function does not really do anything
}
await new Promise(resolve => { setTimeout(resolve, 3000) })}
failure('could not find image');
});
}
async function abc() {
// let options = {
// method: 'HEAD',
// host: 'blog.orange.es',
// path: '/roducto/ok-google-quiero-hablar-con-orange/'
// };
let options = {
method: 'HEAD',
host: 'xnodejs.org',
path: '/en/'
}
try {
var message = await checkAvailability(options)
} catch (e) {
console.log(e)
}
if (typeof message !== "undefined") {
console.log(message)
}
}abc()

--

--

Jonáš Jančařík
Jonáš Jančařík

Written by Jonáš Jančařík

Data analyst, formerly technologist @ECThinkTank (http://medium.com/@ECThinkTank) @EU_Commission think tank.

No responses yet