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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With