4

I am trying to use await-async without try-catch for this:

const getUsers = async (reject, time) => (
  new Promise((resolve, reject) => {
    setTimeout(() => {
      if (reject) {
        reject(....)
      }
      resolve(.....);
    }, time);
  })
);

module.exports = {
  getUsers ,
};

With try-catch block it looks like this:

const { getUsers } = require('./users');

const users = async () => {
  try {
    const value = await getUsers(1000, false);
    .....
  } catch (error) {
    .....
  }
}

users();

How can I write the same code without using the try-catch block?

2
  • 1
    You will have to handle error somewhere. If you want to avoid try-catch in users function, then you have to catch all possible errors in getUsers Commented May 7, 2018 at 8:57
  • Here you can do this stackoverflow.com/a/61833084/6482248 It looks cleaner Commented May 16, 2020 at 7:04

5 Answers 5

10

Using the promise functions then-catch to make the process simpler I use this utils :

// utils.js

const utils = promise => (
  promise
    .then(data => ({ data, error: null }))
    .catch(error => ({ error, data: null }))
);

module.exports = utils;

And then

const { getUsers } = require('./api');
const utils = require('./utils');

const users = async () => {
  const { error, data } = await utils(getUsers(2000, false));
  if (!error) {
    console.info(data);
    return;
  }
  console.error(error);
}

users();

Without using the try-catch block I got the same output, this way makes it better to understand the code.

Sign up to request clarification or add additional context in comments.

1 Comment

Tried this approach with Mongoose to save data to a collection ~ .save() method. Try catch output didn't match. Getting data undefined with this approach, while try block gets the correct response.
3

In Extension to L Y E S - C H I O U K H's Answer:

The Utils Function is actually correct but, make sure to add the return keyword before the promise as shown down below:

// utils.js

const utils = promise => (
  return promise
    .then(data => { [data, null]; })
    .catch(error => { [null, error]; });
);

module.exports = utils;

When Calling in Main Code:

let resonse, error; // any variable name is fine make sure there is one for error and the response

[response, error] = await utils(any_function()); // Make sure that inside the tuple, response is first and error is last like: [response, error].
if (error) console.log(error);

// -- Do Whatever with the Response -- //

Using My Method Would Give you Benefits like:

  1. Your Own Variable Names.
  2. Not Running into Type Safety issues when using Typescript.
  3. Good Reason to Strong Type your code.

Personally, I have been using this in my code lately, and has reduced some many headaches, my code is cleaner, I don't have to stick with the same variable names, especially when working on a large codebase.

Happy Coding :)

See Ya!

2 Comments

Great response! May I ask if (1) You still use this approach and (2) If there are any issues or gotchas we should know about? I've started using it, and I really do like it!
@themthem I'm super late for this, but, no I don't use this approach anymore, instead I wrap the await statement in a try-catch loop, and handle the error in the catch section, this approach is especially good if you're working with typescript.
1

If you have a valid default for the error case you can use the catch method on the getUsers promise and then await a promise whose error will be handled

const users = async () => {
    const value = await getUsers(1000, false).catch(e => null);
}

While this approach should work it should be noted that this may mask the case when getUsers returns null vs when it raises an error, and you will still need to check for the null or get a null access error. All in all I would stick with the try { .. } catch (e) { ... } for most casses

Comments

1

A package I found called await-to-js can also help it.

import to from 'await-to-js';

const [err, users] = await to(getUsers());
if(err) doSomething();

The idea is like Lyes CHIOUKH's method, just a wrapper. Copied the source code here.

/**
 * @param { Promise } promise
 * @param { Object= } errorExt - Additional Information you can pass to the err object
 * @return { Promise }
 */
export function to<T, U = Error> (
  promise: Promise<T>,
  errorExt?: object
): Promise<[U | null, T | undefined]> {
  return promise
    .then<[null, T]>((data: T) => [null, data])
    .catch<[U, undefined]>((err: U) => {
      if (errorExt) {
        Object.assign(err, errorExt);
      }

      return [err, undefined];
    });
}

export default to;

Comments

0

If you have such above single line async/await function, then this would have been clean code for you:

const getUsers = async (time, shouldReject=false) => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (shouldReject) {
          reject(Error('Rejected...'));
        } else {
          resolve(["User1", "User2"]);
        }
      }, time);
    });
}

const userOperation = users => {
  console.log("Operating user", users);
}

// Example 1, pass
getUsers(100)
    .then(users => userOperation(users))
    .catch(e => console.log(e.message));

// Example 2, rejected
getUsers(100, true)
    .then(users => userOperation(users))
    .catch(e => console.log(e.message));

And for multiple await in a single async function, it would good to have try/catch block as below:

const users = async () => {
    try {
        const value = await getUsers(1000, false);
        const value1 = await getUsers2(1000, false);
        ...
    } catch (error) {
        ...
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.