0

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?

Jakob Abfalter
  • 4,980
  • 17
  • 54
  • 94
  • 1
    Yes, only the `return`s and `throw`s in the `async function` itself will be considered. Not those in the callback function passed to `request`. – Bergi May 17 '18 at 11:19
  • 1
    Btw, you can just use the `request-promise` package. And your `queryByName` function should not take a callback, it should just use the returned promise. – Bergi May 17 '18 at 11:20
  • but what if the callback function passed to request is also async? I tried that and it didn't help – Jakob Abfalter May 17 '18 at 11:40
  • Then that function returns a promise to where it is called within `request`. Not helpful - the return value of the callback is ignored (exactly like you did it in `queryByName`). – Bergi May 17 '18 at 11:45

0 Answers0