[Node.js] process.nextTick for converting sync to async
2023-09-14 09:00:49 时间
For example we have a function to check the filesize:
const fs = require('fs'); function fileSize (fileName, cb) { if (typeof fileName !== 'string') { throw new TypeError('filename should be string') } fs.stat(fileName, (err, stats) => { if (err) { return cb(err) } cb(null, stats.size); }); } fileSize(__filename, (err, size) => { if (err) throw err; console.log(`Size in KB: ${size/1024}`); }); console.log('Hello!'); /* Hello! Size in KB: 0.44921875 */
It works fine, but the 'fileSize' function has a problem,
if (typeof fileName !== 'string') { return new TypeError('filename should be string') }
those part of code run in sync, not async, but the rest part of code for 'fileSize' is aysnc function. Normally a function should be always sync or async.
Why? If we call the fileSize with wrong params:
fileSize(1, (err, size) => { if (err) throw err; console.log(`Size in KB: ${size/1024}`); });
It ouput:
/* throw new TypeError('filename should be string') ^ TypeError: filename should be string */
Our console.log() is not running...
To fix it we can use 'process.nextTick', it run before 'event loop' and right after 'call stack is empty':
const fs = require('fs'); function fileSize (fileName, cb) { if (typeof fileName !== 'string') { return process.nextTick( cb, new TypeError('filename should be string') ) } fs.stat(fileName, (err, stats) => { if (err) { return cb(err) } cb(null, stats.size); }); } fileSize(1, (err, size) => { if (err) throw err; console.log(`Size in KB: ${size/1024}`); }); console.log('Hello!'); /* Hello! C:\Users\z000879\learn\maybe\src\process.js:21 if (err) throw err; ^ TypeError: filename should be string */
This time, our 'Hello' was printed out before error was throw.
相关文章
- 00. Node.js 的安装
- js中高级部分知识点总结第二篇
- linux如何安装node.js_centos安装nodejs
- js将秒转化为分钟
- Node.js安装及环境配置之Windows篇详解编程语言
- js滑动触屏事件监听详解编程语言
- 微信小程序:JS 交互逻辑详解编程语言
- JS获取参数个数(包括形参和实参)
- Node.js连接MySQL数据库实践(node连接mysql)
- Exploring the Magic of Linux and Node.js(linuxinode)
- 如何使用Node.js连接Oracle数据库(node连接oracle)
- 使用Node.js实现对MSSQL数据库的连接(node连接 mssql)
- 使用Node.js链接/操作MS SQL数据库(node mssql使用)
- 妙用JS获取Oracle信息的快速方法(js获取Oracle)
- 动态加载js和css(外部文件)
- js点击出现悬浮窗效果不使用JQuery插件
- node.js中的buffer.copy方法使用说明
- node.js中的fs.linkSync方法使用说明
- node.js中的fs.lstat方法使用说明
- 我的Node.js学习之路(三)--node.js作用、回调、同步和异步代码以及事件循环
- JS实现清除指定cookies的方法