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 ...
随机推荐
- Web开发——HTML基础
文档资料参考: 参考:MDN官网 参考:http://www.runoob.com,W3School 参考:https://developer.mozilla.org/zh-CN/docs/Learn ...
- C++11 std::ref使用场景
C++本身有引用(&),为什么C++11又引入了std::ref(或者std::cref)? 主要是考虑函数式编程(如std::bind)在使用时,是对参数直接拷贝,而不是引用.如下例子: # ...
- python中的单例
使用__new__ 因为一个类每一次实例化的时候,都会走它的__new__方法.所以我们可以使用__new__来控制实例的创建过程,代码如下: class Single: instance = Non ...
- iOS开发笔记错误集
错误类型列举 错误类型A:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) 错误类型B:EXC_BREAKPOINT (code=EXC_A ...
- redis集群(jedis)批量删除同一前缀
public Set<String> getByPrefix(String key) { Set<String> setResult = new HashSet<> ...
- java8模拟grouby方法
public class ListUtils{ /** * list 集合分组 * * @param list 待分组集合 * @param groupBy 分组Key算法 * @param < ...
- Nginx技术研究系列5-动态路由升级版
前几篇文章我们介绍了Nginx的配置.OpenResty安装配置.基于Redis的动态路由以及Nginx的监控. Nginx-OpenResty安装配置 Nginx配置详解 Nginx技术研究系列1- ...
- 零基础快速入门web学习路线(含视频教程)
下面小编专门为广大web学习爱好者汇总了一条完整的自学线路:零基础快速入门web学习路线(含视频教程)(绝对纯干货)适合初学者的最新WEB前端学习路线汇总! 在当下来说web前端开发工程师可谓是高福利 ...
- springmvc学习路线1-基本配置
1.第一个springmvc实例helloword 关键点拨 1.1 web.xml文件的配置 <servlet> <servlet-name>springMVC</se ...
- Servlet+纯java+MySQL实现课程信息的增删改查
Dbutil: package com.zh.util; import java.sql.Connection; import java.sql.DriverManager; import java. ...