Quantcast
Channel: CNode:Node.js专业中文社区
Viewing all articles
Browse latest Browse all 14821

升级 async/await 指南, promise / co / eslint etc

$
0
0

promise

Long Long Ago, 未catch 的 promise rejection 会被无声吞没, 在 Node

  • v6 中, 会自动打印一句 unhandledRejection
  • v7 中, 将 v6 的行为 deprecated, 提示以后会导致整个程序 crash, 使用 process.on('unhandledRejection', err => blabla)来解除 deprecate warning 升级 async await 之后, 调用 async function 如果没有 catch, 也是 unhandledRejection.

解决

使用 https://github.com/sindresorhus/loud-rejection在 application, 或者 framework 的开始处调用 require('loud-rejection')()即可, 不需手动 attach process unhandledRejection 事件 不要在 library 中使用

ESLint

使用 babel-eslint 作为 parser 的请手动忽略… 之前在 v6 的时候, 所有的 ES6 feature 都是可以使用 parserOptions.ecmaVersion = 6完成 parse 的

parserOptions:
  ecmaVersion: 6

因为后端不使用 babel, ESLint 需修改 parserOptions.ecmaVersion = 8 async/await 进入的是 ES8(aka ES2017) 标准

untitled1.png

co / co.wrap 迁移

co调用

- return co(function*(){ /* blabla */ })
+ return (async () => { /* blabla */ })()

co.wrap调用

- const fn = co.wrap(function*(arg1, arg2) { 
-   /* blabla */ 
- })

+ const fn = async function(arg1, arg2) { 
+   /* blabla */ 
+ }

yield -> await

yield 可以处理 object / array / generator 等, 变成 await

  • object: 使用 require('bluebird').props / require('promise.obj')
  • array: 使用 Promise.all即可
  • generator: 使用 co.wrap再次包装成一个 async function

mocha + istanbul

mocha 不用动, 只要 node 支持就行 istanbul 还有个 parse 的过程, 当前 latest 0.4.5 不能parse async/await, 需要 npm i istanbul@next --save-dev即可

CI

以前的 Travis CI node version 都是 v4 / v5 / v6 / v7 请都删掉, 保留一个 v7.6.0即可 例 https://github.com/magicdawn/impress-router/commit/d2abeb5f7c69fb26ca925739e86e70605e410680

其他

欢迎补充, 不对请指正… 谢谢


Viewing all articles
Browse latest Browse all 14821

Trending Articles