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. H/s:哈希率单位转换

    哈系率说明 挖矿能力是通过寻找矿工可以执行的地块的尝试次数来衡量的.每次尝试都包括创建一个唯一的块候选项,并通过SHA-256d(一种加密哈希函数)创建块候选项的摘要.或者,简而言之,哈希.由于这是一 ...

  2. hive sqoop,sqoop-hive import data

    https://segmentfault.com/a/1190000002532293 https://www.zybuluo.com/aitanjupt/note/209968 create tab ...

  3. 6、Flutter Error waiting for a debug connection: ProcessException: adb did not report f(转)

    1.错误信息 Error waiting for a debug connection: ProcessException: adb did not report forwarded port 2.解 ...

  4. CSS中list-style详解

    取消默认的圆点和序号可以这样写list-style:none;, list的属性如下: list-style-type:square;//正方形 list-style-position:inside; ...

  5. [js]变量提升-关于条件

    条件函数变量提示于全局中函数变量提升不一样. 条件中: 函数变量提升, 只是声明(现新版本浏览器中) if(g()){ function g() { return true } console.log ...

  6. Py中查看数据类型【转载】

    转自:https://www.jianshu.com/p/bb5cc438e3b2 1.内置函数isinstance(object, (type1,type2...)) isinstance('con ...

  7. CDN和智能DNS原理和应用 (原)

    CDN是什么? CDN的全称是Content Delivery Network,即内容分发网络. CDN是构建在网络之上的内容分发网络,依靠部署在各地的边缘服务器,通过中心平台的负载均衡.内容分发.调 ...

  8. c# 传入c++dll 回调函数输出byte 导致 bug

  9. windows将文件夹映射为虚拟磁盘

    subst X: e:123 将e盘下的123文件夹映射为x盘,123的容量即x盘容量 subst X: /t 删除映射的x盘

  10. JSP 修改不能编辑

    JSP做修改功能时候,有的时候,某些值要设置成只读状态,不能修改,刚开始做的时候,出现了修改之后值传不到后台的情况,由于刚出来工作不久,不是很了解这个.思索了半天,才发现是由于这个属性的缘故.浪费了大 ...