且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用await异步获取数据而无需尝试捕获

更新时间:2023-09-26 21:27:34

使用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.