Practical Node.js (2018版) 14章, async code in Node
Asynchronous Code in Node
历史上,Node开发者只能用回调和事件emitters。
现在可以使用一些异步的语法:
- async module
- Promises
- Async/await funcitons
Promise
在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的更多相关文章
- 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有很大的区 ...
- Practical Node.js (2018版) 第9章: 使用WebSocket建立实时程序,原生的WebSocket使用介绍,Socket.IO的基本使用介绍。
Real-Time Apps with WebSocket, Socket.IO, and DerbyJS 实时程序的使用变得越来越广泛,如传统的交易,游戏,社交,开发工具DevOps tools, ...
- Practical Node.js (2018版) 第7章:Boosting Node.js and Mongoose
参考:博客 https://www.cnblogs.com/chentianwei/p/10268346.html 参考: mongoose官网(https://mongoosejs.com/docs ...
- Practical Node.js (2018版) 第5章:数据库 使用MongoDB和Mongoose,或者node.js的native驱动。
Persistence with MongoDB and Mongoose https://github.com/azat-co/practicalnode/blob/master/chapter5/ ...
- Practical Node.js (2018版) 第10章:Getting Node.js Apps Production Ready
Getting Node.js Apps Production Ready 部署程序需要知道的方面: Environment variables Express.js in production So ...
- 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.一种 ...
- 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 ...
- Practical Node.js (2018版) 第4章: 模版引擎
Template Engines: Pug and Handlebars 一个模版引擎是一个库或框架.它用一些rules/languages来解释data和渲染views. web app中,view ...
- [译]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 ...
随机推荐
- 《nginx - 基本操作/配置》
一:基本操作 - 开启 Nginx nginx -c nginx.conf - Nginx 的平滑重启 kill -HUP nginx主进程号(平滑重启) - 停止 Nginx * Kill -Q ...
- python摸爬滚打之day20--多继承,MRO和C3算法
1.新式类和经典类 在python2.2之前, 基类如果不写(), 则表示为经典类; 在python2.2之后, 经典类不复存在, 只存在新式类. 如果基类谁都不继承的话, 则默认继承object. ...
- 使用hashlib进行文件校验
import hashlib import os path = r'D:\CentOS 64 位' def file_md5(path): """ 文件校验 :param ...
- JAVA微信公众号网页开发 —— 用户授权获取openid
官方文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842 HttpClientUtil.java packa ...
- ajax 显示,删除,批量删除,修改反填功能实现
1.页面代码 <body> <h1>显示所有员工信息</h1> <input id="Button1" type="button ...
- react native出现 undefined is not a function_this4.错误函数无法识别
该函数可能里可能有this,的上个函数this要绑定bind(this)
- C#文件流的读写
1.文件流写入的一般步骤 1.定义一个写文件流 2.定义一个要写入的字符串 3.完成字符串转byte数组 4.把字节数组写入指定路径的文件 5.关闭文件流 2.文件流读入的一般步骤 1.定义一个读文件 ...
- .sh文件启动 jenkins
https://jenkins.io/index.html Jenkins的war包下载http://192.168.89.132:8080/jenkins /home/xmh/.jenkins ...
- i2c状态机方法设计-verilog
2010-09-05 21:04:00 verilog语言基础学的差不多了.接着就是看看华为的语言编写规范.状态机设计方法是fpga的重要设计方法.所以我要记上一笔. 只要会FSM方法,用fpga编写 ...
- Linux configure,make,make install
https://www.cnblogs.com/tinywan/p/7230039.html https://www.sohu.com/a/191735643_505857 https://blog. ...