Get data using await async without try catch

后端 未结 5 1822
抹茶落季
抹茶落季 2020-12-15 02:11

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

<
5条回答
  •  难免孤独
    2020-12-15 02:45

    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.

提交回复
热议问题