Asynchronous Code in Node


历史上,Node开发者只能用回调和事件emitters。

现在可以使用一些异步的语法:

  • async module
  • Promises
  • Async/await funcitons

Promise

the docs,

在hook下,一个基本的promise的运行。

Promises不是取代callback,它仍然使用callback。

例子:

这是传统的callback用法

function myAsyncTimeoutFn(data, callback) {
setTimeout(() => {
callback()
}, 1000)
} myAsyncTimeoutFn('just a silly string argument', () => {
console.log('Final callback is here')
})

Promise改变了代码的布局:

这是模仿Promise原理的代码。返回一个Promise对象。

function myAsyncTimeoutFn(data) {

  let _callback = null
setTimeout( () => {
if ( _callback ) _callback()
}, 1000) return {
then(cb) {
_callback = cb
}
}
} myAsyncTimeoutFn('just a silly string argument').then(() => {
console.log('Final callback is here')
})

这个对象有内有一个特别的方法then。

执行这个方法then,会设置回调_callback变量。

最后调用event queue的任务setTimeout()。执行_callback()。

⚠️:_callback这种写法只是告诉其他开发者这个方法是私有的。

如何处理错误?很简单在返回对象内的then方法添加一个错误参数。

// 使用file system模块中的readFile()方法,异步函数。
const fs = require('fs') function readFilePromise( filename) {
let _callback = () => {}
let _errorCallback = () => {} fs.readFile(filename, (error, buffer) => {
if (error) _errorCallback(error)
else _callback(buffer)
}) return {
then(cb, errCb) {
_callback = cb
_errorCallback = errCb
}
}
} readFilePromise('package.json').then( buffer => {
console.log(buffer.toString() )
process.exit(0)
}, err => {
console.error(err)
process.exit(1)
})

语法

p.then(onFulfilled[, onRejected]);

p.then((value) => {
// fulfillment
}, (reason) => {
// rejection
});

1. 执行readFilePromise函数

2. fs.readFile()读数据,并存入内存,等待后续处理。

3. return返回一个对象。

4.调用对象的then方法。

5.从event queue中读取回调函数

(error, buffer) => {
if (error) _errorCallback(error)
else _callback(buffer)
})

改变一下上面的代码:

readFilePromise('package.jsqn').then( buffer => {

就会在terminal 上打印错误信息:

{ [Error: ENOENT: no such file or directory, open 'package.jsqn']
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: 'package.jsqn' }

总结:

我们没有使用回调callback参数在主函数中传递值,相反,我们使用callback参数在then方法内。

callback参数的值是一个函数会在之后处理。就像标准的回调函数一样。


Async functions

一个promise的wrapper。

优势:async/await函数的语法在其他语言如C#内已经存在。

下面使用async/await来重写

Practical Node.js (2018版) 14章, async code in Node的更多相关文章

  1. Practical Node.js (2018版) 13章, Node HTTP/2 Servers

    新增的章节. If you are not using HTTP/2, then you are losing out on big improvements. HTTP/2相比http/1有很大的区 ...

  2. Practical Node.js (2018版) 第9章: 使用WebSocket建立实时程序,原生的WebSocket使用介绍,Socket.IO的基本使用介绍。

    Real-Time Apps with WebSocket, Socket.IO, and DerbyJS 实时程序的使用变得越来越广泛,如传统的交易,游戏,社交,开发工具DevOps tools, ...

  3. Practical Node.js (2018版) 第7章:Boosting Node.js and Mongoose

    参考:博客 https://www.cnblogs.com/chentianwei/p/10268346.html 参考: mongoose官网(https://mongoosejs.com/docs ...

  4. Practical Node.js (2018版) 第5章:数据库 使用MongoDB和Mongoose,或者node.js的native驱动。

    Persistence with MongoDB and Mongoose https://github.com/azat-co/practicalnode/blob/master/chapter5/ ...

  5. Practical Node.js (2018版) 第10章:Getting Node.js Apps Production Ready

    Getting Node.js Apps Production Ready 部署程序需要知道的方面: Environment variables Express.js in production So ...

  6. Practical Node.js (2018版) 第3章:测试/Mocha.js, Chai.js, Expect.js

    TDD and BDD for Node.js with Mocha TDD测试驱动开发.自动测试代码. BDD: behavior-driven development行为驱动开发,基于TDD.一种 ...

  7. Practical Node.js (2018版) 第8章:Building Node.js REST API Servers

    Building Node.js REST API Servers with Express.js and Hapi Modern-day web developers use an architec ...

  8. Practical Node.js (2018版) 第4章: 模版引擎

    Template Engines: Pug and Handlebars 一个模版引擎是一个库或框架.它用一些rules/languages来解释data和渲染views. web app中,view ...

  9. [译]How to Install Node.js on Ubuntu 14.04 如何在ubuntu14.04上安装node.js

    原文链接为 http://www.hostingadvice.com/how-to/install-nodejs-ubuntu-14-04/ 由作者Jacob Nicholson 发表于October ...

随机推荐

  1. Chrome 调试技巧

    Chrome 调试技巧 1.alert 这个不用多说了,不言自明. 可参考:https://www.cnblogs.com/Michelle20180227/p/9110028.html 2.cons ...

  2. odoo中self的使用

    一:self是什么 目前新版的Odoo中使用到的self,是对  游标cr.用户ID.模型.上下文.记录集.缓存  的封装. 我们可以通过 self.XX 获取到这些封装的东西,比如:self.cr. ...

  3. windows7,python3使用time.strftime()函数报ValueError: embedded null byte

    windows7环境下,执行代码报ValueError: embedded null byte时,在原代码前面加一行代码:locale.setlocale(locale.LC_ALL,'en')即可解 ...

  4. Spring Boot事务管理(中)

    在上一篇 Spring Boot事务管理(上)的基础上介绍Spring Boot事务属性和事务回滚规则 . 4 Spring Boot事务属性 什么是事务属性呢?事务属性可以理解成事务的一些基本配置, ...

  5. TP框架中分页类的使用

    public function test(){ $m=M('Message'); import('ORG.Util.Page');// 导入分页类 $count = $m->count();// ...

  6. Jedis连接 HelloWorld实现

    建一个Maven项目, pom里加下jedis依赖, <dependency> <groupId>redis.clients</groupId> <artif ...

  7. 关于 spring MVC 配置自动扫描中 use-default-filters 属性

    1.springMVC 设置扫描 Bean 的两种常见写法 1.1.先看第一种常见的配置:默认 <!-- 配置Controller扫描 --> <context:component- ...

  8. cocos2d-x 贡献一个oss上传脚本

    平常写前端项目和H5游戏时特别频繁的一个操作就是上传到oss上,特别浪费时间.所以用ali-oss写了一个脚本.配置属性后直接npm run oss就能上传到oss上了.再也不需要手动操作.现在是脚本 ...

  9. 微信内置安卓x5浏览器请求超时自动重发问题处理小记

    X5内核  请求超时后会自动阻止请求返回并由代理服务器将原参数重新发送请求到服务层代码.但由于第一次请求已经请求到服务器,会导致出现重复下单.支付等重大问题. 该问题由于腾讯x5浏览器会自动阻止第一次 ...

  10. 压缩图片 Image

    图片压缩 class resizeImg: """缩略图""" def __init__(self,**args): self.args_k ...