I am executing the following in node 8.10 and do not understand why it will not wait for the promise to be resolved:
The root call is like this
searcher.queryByName(companyname, (err, companies) => {
if (err) {
logger.error(`Searcher Error during ${provider} Search for ${companyname} ${JSON.stringify(body)}`, err);
res.sendStatus(500);
}
else {
res.set('Content-Type', 'application/json');
logger.info(`Searcher Found ${companies.length} results for queryByName search for provider ${provider}`);
const json = JSON.stringify(companies);
res.send(json);
}
});
Inside the searcher I have this
async queryByName(name, cb) {
try {
const pageUrlOptions = {
url: pageURL,
timeout: 30000,
encoding: null
};
const response = await Requestor.sendHttpRequest(pageUrlOptions);
if (response.statusCode === 200) { cb(false, "Result"); }
else { cb(response.statusCode); }
} catch(e) {
cb(err);
}
}
the method in the Requestor looks like this:
static async sendHttpRequest(options) {
if (!options.timeout) options.timeout = 30000;
request(options, (err, response) => {
if( err ) { throw err; }
else { return response; }
})
}
What will happen is this:
TypeError: Cannot read property 'statusCode' of undefined
If I change the method to:
static async sendHttpRequest(options) {
return new Promise((resolve, reject) => {
if (!options.timeout) options.timeout = 30000;
request(options, (err, response) => {
if( err ) { reject(err); }
else { resolve(response); }
})
});
}
It works.
I thought that async declared functions will automatically wrap returns and error throwing into a Promise and I don't need the constructor, but why does this not work in this case? Is it because I am using callbacks in the root function?