Thursday, 20 September 2018

Unhandle rejection promise async await chain

I'm fairly new to async await in javascript so this question might be something I don't know.

I have this

  async foo(req, res, next) {
    try {
      await scan(req.params.stack);
      res.send('ok');
    } catch (err) {
      res.status(500).send('fail');
    }
  }

async scan(stack) {
  try {
    const libs = [1,2,3];
    const promises = libs.map(async l => analyze(stack, l)
      .catch((err) => { throw new Error(err); }));
    return q.allSettled(promises)
      .then((results) => {
        const rejected = results.filter(r => r.state === 'rejected');
        if (rejected.length === results.length) throw new Error('Failed');
        return results;
      })
      .catch((err) => {
        throw new Error(err);
      });
  } catch (err) {
    throw new Error(err);
  }
}

async function analyze(stack, libraries) {
  try {
    const config = await buildConfiguration(stack, libraries);
    return await databaseInsertion(vulnsObject);
  } catch (err) {
    return Promise.reject('Error while trying to analyze libs');
  }
}

Somehow I'm getting this wild warning and I don't know where I am not catching the error.

Of course I'm making build configuration fail in order to test the error, but instead of having a normal flow cathing the error i got this:

(node:415) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3): Error: Error while trying to analyze libs

Am I using async await good? Is there any patter i should follow in order to chain async await?

The wild thing is that the foo function works good, meaning that the res.status.(500).send('fail'); works and Im getting the response

When I was using normal promises this error didn't appear.

I'm really stucked here



from Unhandle rejection promise async await chain

No comments:

Post a Comment