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 ...
随机推荐
- 使用docker容器运行MySQL数据库并持久化数据文件
1.下载mysql镜像 # docker pull mysql 2.启动mysql容器 # docker run -itd -v /data:/var/lib/mysql -p 33060:3306 ...
- ionic1滑动时间选择器
上图: 1.derective代码 .directive('monthPicker', function ($ionicScrollDelegate) { return { restrict: 'E' ...
- WCF中的ServiceHost初始化两种方式
1 代码方式 using(ServiceHost host=new ServiceHost(typeof(HelloWordService))) { host.AddServiceEndpoint(t ...
- EntityFreamWork 项目总结
前段时间一直在忙着处理一个B2C的商城项目,未来得整理这次项目的心得,今天偶有空闲便写下这篇文章以记录整个项目的设计及自我总结. 这个项目是我综合传智播客教学基础将传统三层架构与EntityFrame ...
- Ethzasl MSF源码阅读(2):百川汇海
这里有个感觉,就是百川汇海.即IMU数据和相机的消息数据都汇集到msf_core进行处理.接上一篇, 1. 查看IMUHandler_ROS::IMUCallback和IMUHandler_ROS:: ...
- iOS UI基础-21 WKWebView
WKWebView,直接显示网页,需要引入第三方类:https://github.com/marcuswestin/WebViewJavascriptBridge 加上进度条代码,很完美使用 webV ...
- 基于Jenkins实现持续集成【持续更新中】
持续集成 1.什么是持续集成:Continuous integration (CI)持续集成是一种软件开发实践,即团队开发成员经常集成他们的工作,通常每个成员每天至少集成一次,也就意味着每天可能会发生 ...
- [转载]get、post异同
1. get是从服务器上获取数据,post是向服务器传送数据. 2. get是把参数数据队列加到提交表单的ACTION属性所指的URL中,值和表单内各个字段一一对应,在URL中可以看到.post是通过 ...
- GoldenGate for Java Adapter介绍一(原理篇)
前言 Oracle Goldengate在很早前就推出了一个for java的版本,主要目的是方便把关系型数据实时写入到不支持的目标端,如JMS或Redis等key value数据库.在Hadoop刚 ...
- GitHub linux 提交文件及403错误处理
$git clone "Clone with HTTPS(自己生成的地址,如:https://github.com/******(用户名)/test.git)" 这时在你git ...