优雅地 `async/await`

栏目: Node.js · 发布时间: 7年前

内容简介:比如下面这样,一个简单的 Node.js 中使用像这样的异步场景,Node.js 中会有很多。如果都通过

async/await 虽然取代了回调,使用类似同步的代码组织方式让代码更加简洁美观,但错误处理时需要加 try/catch

比如下面这样,一个简单的 Node.js 中使用 async/await 的场景:

const fetch = require("node-fetch");

async function getData() {
  const url = "https://api.github.com/users/wayou";
  try {
    const response = await fetch(url);
    const data = await response.json();
    console.log(data);
  } catch (error) {
    throw error;
  }
}

getData();

像这样的异步场景,Node.js 中会有很多。如果都通过 try/catch 来错误处理,数量多了之后也是不太美观的。

将异步进行一层封装

因为本质上 async/awaitPromise ,我们可以封装一个简单的方法,将错误处理变得更优雅。

比如下面这样:

function await2js(promise) {
  return promise.then(result => [undefined, result]).catch(error => [error, undefined]);
}

该方法始终返回两个结果,第一个是错误,第二个是数据,这和 Node.js 中回调的入参 (err,data)=>void 是一致的,使得这层包装很 Node.js,一点也不会感到奇怪。

所以改造后的使用示例:

async function getData() {
  const url = "https://api.github.com/users/wayou";
  const [error, response] = await await2js(fetch(url));
  if (error) {
    throw error;
  }

  const [error2, data] = await await2js(response.json());
  if (error2) {
    throw error2;
  }

  console.log(data);
}

这层封装针对单个 await ,不像 try/catch 那么粗犷一下子包含再次 await 。也不是说 try/catch 不能精细地处理错误,但脑补一下把上面两次 await 都用 try/catch 的模样。

当然,如果嫌麻烦,也可通过 Promise.all() 或 Promise 的链式调用将多次 await 操作合并,只处理一次错误。

TypeScript 版本

function await2js<T, K = Error>(promise: Promise<T>) {
  return promise
    .then<[undefined, T]>((response: T) => [undefined, response])
    .catch<[K, undefined]>((error: K) => [error, undefined]);
}

这里有个相应的 npm 包便是做这事情的 await-to-js


以上所述就是小编给大家介绍的《优雅地 `async/await`》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Linux Programming Interface

The Linux Programming Interface

Michael Kerrisk / No Starch Press / 2010-11-6 / GBP 79.99

The Linux Programming Interface describes the Linux API (application programming interface)-the system calls, library functions, and other low-level interfaces that are used, directly or indirectly, b......一起来看看 《The Linux Programming Interface》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具