使用await异步获取数据而无需尝试捕获 [英] Get data using await async without try catch

查看:56
本文介绍了使用await异步获取数据而无需尝试捕获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为此,我尝试使用不带try-catch的await-async:

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 ,
};

使用try-catch块,它看起来像这样:

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();

如何在不使用try-catch块的情况下编写相同的代码?

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

推荐答案

使用then-catch函数,使过程更简单,我使用以下utils:

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;

然后

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();

在不使用try-catch块的情况下,我得到了相同的输出,这样可以更好地理解代码.

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

这篇关于使用await异步获取数据而无需尝试捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆