Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Async function works with a callback does not work with await

I am trying to integrate into my code an async library function. It works fine as:

client.checkPermission(checkPermissionRequest, (err, response) => {
  if (err || response?.permissionship !== HAS_PERMISSION) {
    const e = err || new Error('You do not have access to event:', id);
    res.code(404).send({ error: e });
  }
});

I want to rewrite it in an "await form" and this does not work. I have been trying:

const response = await client.checkPermission(checkPermissionRequest);

When I run the await code, it fails with: Error: Incorrect arguments passed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Why could this be happening and how could I fix this?

>Solution :

await doesn’t magically make a callback-based API return a promise.

You can however, wrap the call in a promise:

const response = await new Promise((resolve, reject) => {
    client.checkPermission(checkPermissionRequest, (err, response) => {
        if (err) return reject(err);

        return resolve(response);
    });
});

This is called "promisification". If you’re a little confused as to how resolve and reject work, maybe the examples in MDN could help with that.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading