try/catch

在使用Async/Await前,我们可能这样写:

const main = (paramsA, paramsB, paramsC, done) => {
funcA(paramsA, (err, resA) => {
if (err) return done(err)
return funcB(paramsB, (err, resB) => {
if (err) return done(err)
funcC(paramsC, (err, resC) => {
if (err) return done(err)
// (╯°□°)╯︵ ┻━┻
return done(null, { resA, resB, resC })
})
})
})
}

采用了Async/Await后:

const main = async (paramsA, paramsB, paramsC) => {
const resA = await funcA(paramsA)
const resB = await funcB(paramsB)
const resC = await funcC(paramsC)
// \(T.T)/
return { resA, resB, resC }
}

然后你会发现,我们没有处理错误异常的情况,然后你可能会这么写:

const main = async (paramsA, paramsB, paramsC) => {
let resA
let resB
let resC
try {
resA = await funcA(paramsA)
} catch (error) {
throw error
}
try {
resB = await funcB(paramsB)
} catch (error) {
throw error
}
try {
resC = await funcC(paramsC)
} catch (error) {
throw error
}
// (o.o;)
return { resA, resB, resC }
}

可能你不需要单独处理每个错误,然后你就这么写:

const main = async (paramsA, paramsB, paramsC) =>
try {
const resA = await funcA(paramsA)
const resB = await funcB(paramsB)
const resC = await funcC(paramsC)
// (^.^')
return { resA, resB, resC }
} catch (error) {
throw error
}
}

但是,很快滴,你发现代码报了这样一个错误:(注意如果你用了Node.js,可能对这个错误不陌生)

(node: xxx) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: y): Error: some sort of error
(node: xxx) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
// (-.-;)

然后你会想,我草,哪里的原因。然后你花了20多分钟,去找问题。问题很简单就是:

你抛出了一个异常,但是你没有捕捉它和处理它。

因为Async/Await函数返回的是一个Promise,所以我们想下怎么解决它:

const main = async (paramsA, paramsB, paramsC) => {
try {
const resA = await funcA(paramsA)
const resB = await funcB(paramsB)
const resC = await funcC(paramsC)
return { resA, resB, resC }
} catch (error) {
// sure it's thrown, but who catches it??
throw error
}
}
// somewhere else...
main()
.then(d => { // do things with the result })
.catch(e => { // handle that error! })

在.catch方法里面捕捉错误。但如果我真的想单独处理某个错误呢:

const main = async (paramsA, paramsB, paramsC) => {
const resA = await funcA(paramsA)
const resB = await funcB(paramsB).catch(e => { // things unique to this error })
const resC = await funcC(paramsC)
return { resA, resB, resC }
}
// ... all we need is this `.catch` to handle all of them.
main()
.then(d => { // do things with the result })
.catch(e => { // handle all other errors!! })

用Mocha, Sinon, and Chai进行测试

测试Async / Await函数非常简单,首先,你只要记住这三件事:

1 不要把异步函数和promise混一起

const thing = (params, done) => {
ApiCall(params, async (err, data) => {
if (err) return done(err)
const things = await OtherApiCall(data)
return done(null, things)
})
}

像上面这样,真的会崩溃的。

2 记住Async / Await返回了一个Promise

3 如果你在Mocha测试里面返回了promise,mocha测试会处理好它,你不用担心。

ok.开始:

我们有一个主文件main.js

// main.js
const main = async (paramsA, paramsB, paramsC) => {
const resA = await apiA.create(paramsA)
const resB = await apiB.delete(paramsB)
const resC = await apiC.update(paramsC)
return { resA, resB, resC }
}

然后我们的测试文件就这样写:

// test.js
const expect = require('chai').expect
const sinon = require('sinon')
const main = require('main.js')
const apiA = require('apiA')
const apiB = require('apiB')
const apiC = require('apiC')
describe('Main Function', () => {
let apiAstub
let apiBstub
let apiCstub
beforeEach(() => {
apiAstub = sinon.stub(apiA, 'create')
apiBstub = sinon.stub(apiB, 'delete')
apiCstub = sinon.stub(apiC, 'update')
})
afterEach(() => {
apiAstub.restore()
apiBstub.restore()
apiCstub.restore()
})
it('should handle errors if apiA.create() fails', () => {
apiAstub.throws('error for apiA.create()')
// 在这里处理一下。因为返回的是promise,catch一下就行
return main('a', 'b', 'c').catch((e) => {
//mocha会等promise返回或者在这里异常
expect(e).to.equal('error for apiA.create()')
})
})
it('should handle errors if apiB.delete() fails', () => {
apiAstub.returns('success a')
apiBstub.throws('error for apiB.delete()')
return main('a', 'b', 'c').catch((e) => {
expect(e).to.equal('error for apiB.create()')
})
})
it('should handle errors if apiC.update() fails', () => {
apiAstub.returns('success a')
apiBstub.returns('success b')
apiCstub.throws('error for apiC.delete()')
return main('a', 'b', 'c').catch((e) => {
expect(e).to.equal('error for apiC.create()')
})
})
it('should return the responses of all functions if all api calls succeed', () => {
apiAstub.returns('success a')
apiBstub.returns('success b')
apiCstub.throws('success c')
return main('a', 'b', 'c').then((res) => {
expect(res).to.deep.equal({
resA: 'success a',
resB: 'success b',
resC: 'success c',
})
})
})
})

不用第三方库,测试用例照写不误。

Async / Await和Node核心模块一起使用

你可能会想要这么写:

const fs = require('fs')
async function readThings () {
const file = await fs.readFile('./file.txt', 'utf8')
// file值不存在
return file
}

但实际上:readFile 并没有返回promise,这样写是有问题的

很幸运滴是Node.js8 util方法提供了一个method,promisify:

const fs = require('fs')
const { promisify } = require('util')
const readFile = promisify(fs.readFile)
async function readThings () {
const file = await readFile('./file.txt', 'utf8')
// 成功!
return file
}

Async / Await在AWS SDK中使用

const aws = require('aws-sdk')
async function getEc2Info () {
const ec2 = new aws.EC2()
const instances = await ec2.describeInstances()
// do things with instances
}

如果你像上面那样写,你会发现它不起作用。你会想用util.promisify,但其实它也不能用。

实际上,这样就行了:

const aws = require('aws-sdk')
async function getEc2Info () {
const ec2 = new aws.EC2()
const instances = await ec2.describeInstances().promise() // <--
// Actually do things with instances!
}

以上就是今天的内容,感谢阅读。

原文:https://start.jcolemorrison.com/5-tips-and-thoughts-on-async-await-functions/#testing

作者知乎/公众号:前端疯

(译文)学习ES6非常棒的特性——Async / Await函数的更多相关文章

  1. (译文)学习ES6非常棒的特性-深入研究var, let and const

    Var var firstVar; //firstVar被声明,它的默认值是undefined var secondVar = 2; //secondVar被声明,被赋值2 先看一个例子: var i ...

  2. (译文)学习ES6非常棒的特性-字符串常量基础

    字符串常量基础 在ES2015之前我们是这么拼接字符串的: var result = 10; var prefix = "the first double digit number I le ...

  3. 使用ES6新特性async await进行异步处理

    我们往往在项目中会遇到这样的业务需求,就是首先先进行一个ajax请求,然后再进行下一个ajax请求,而下一个请求需要使用上一个请求得到的数据,请求少了还好说,如果多了,就要一层一层的嵌套,就好像有点c ...

  4. 微信小程序捕获async/await函数异常实践

    背景 我们的小程序项目的构建是与web项目保持一致的,完全使用webpack的生态来构建,没有使用小程序自带的构建功能,那么就需要我们配置代码转换的babel插件如Promise.Proxy等:另外, ...

  5. ES6非常棒的特性-解构

    https://blog.csdn.net/maoxunxing/article/details/79772946

  6. .net 4.5 新特性 async await 一般处理程序实例

    using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Sys ...

  7. ES8之async/await学习随笔

    详细学习参考文档: 阮一峰老师的博客,覆盖知识点ES6/7/8/9,本篇学习笔记对阮老师的关于async/await文档中的知识点进行分点总结 在ES8中加入async/await新特性后,很明显带来 ...

  8. async/await,了解一下?

    上一篇博客我们在现实使用和面试角度讲解了Promise(原文可参考<面向面试题和实际使用谈promise>),但是Promise 的方式虽然解决了 callback hell,但是这种方式 ...

  9. ES7 Async/Await 陷阱

    什么是Async/Await ES6新增了Promise函数用于简化项目代码流程.然而在使用promise时,我们仍然要使用callback,并且并不知道程序要干什么,例如: function doS ...

随机推荐

  1. org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException

    1.错误描述 usage: java org.apache.catalina.startup.Catalina [ -config {pathname} ] [ -nonaming ] { -help ...

  2. python 字符串格式化输出 %d,%s及 format函数

    旧式格式化方式:%s,%d 1.顺序填入格式化内容 s = "hello %s, hello %d"%("world", 100) print(s) 结果: ' ...

  3. 通过ApplicationContext.getBean(beanName)动态加载数据。

    一,前台数据 $.ajax({ url: '/intra/coe/order/ploadTable.htm', type: 'POST', dataType: 'json', data: {keyId ...

  4. 含隐变量模型求解——EM算法

    1 EM算法的引入1.1 EM算法1.2 EM算法的导出2 EM算法的收敛性3EM算法在高斯混合模型的应用3.1 高斯混合模型Gaussian misture model3.2 GMM中参数估计的EM ...

  5. Cglib及其基本使用

    前言 最近一直在看Spring源码,其实我之前一直知道AOP的基本实现原理: 如果针对接口做代理默认使用的是JDK自带的Proxy+InvocationHandler 如果针对类做代理使用的是Cgli ...

  6. 如何利用wireshark破解网站密码

    在有进行破解意愿的想法诞生之前,博主得先来给各位泼一盆凉水,本文介绍的方法破解http的轻而易举,而对于https的就算了.因为Wireshark 没有session key ,不能解密SSL数据流. ...

  7. 序列化、反序列化(Serializable特性)

    //需要被实例化的类 using System.Collections; using UnityEngine; [Serializable] public class SerializableClas ...

  8. 设计模式——享元模式(C++实现)

    #include <iostream> #include <string> #include <map> #include <vector> #incl ...

  9. linux 目录详解

    /bin bin是binary的缩写.这个目录沿袭了UNIX系统的结构,存放着使用者最经常使用的命令.例如cp.ls.cat,等等. /boot 这里存放的是启动Linux时使用的一些核心文件. /d ...

  10. setup命令的安装

    2018-03-01  10:25:18 最小化安装的Linux系统,setup命令使用不了 安装方法:yum install setuptool    #安装完以后,只要直接输入 setup,就会出 ...