Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get data using await async without try catch

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?

like image 610
L Y E S - C H I O U K H Avatar asked Dec 23 '22 07:12

L Y E S - C H I O U K H


1 Answers

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.

like image 121
L Y E S - C H I O U K H Avatar answered Jan 05 '23 14:01

L Y E S - C H I O U K H