[Node.js] process.nextTick for converting sync to async
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/}`);
});
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(, (err, size) => {
if (err) throw err;
console.log(`Size in KB: ${size/}`);
});
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(, (err, size) => {
if (err) throw err;
console.log(`Size in KB: ${size/}`);
});
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.
[Node.js] process.nextTick for converting sync to async的更多相关文章
- Node.js & process.env & OS Platform checker
Node.js & process.env & OS Platform checker Window 10 Windows 7 ia32 CentOS $ node # process ...
- Node.js process 模块常用属性和方法
Node.js是常用的Javascript运行环境,本文和大家发分享的主要是Node.js中process 模块的常用属性和方法,希望通过本文的分享,对大家学习Node.js http://www.m ...
- Node.js 101(2): Promise and async
--原文地址:http://blog.chrisyip.im/nodejs-101-package-promise-and-async 先回想一下 Sagase 的项目结构: lib/ cli.js ...
- how to config custom process.env in node.js
how to config custom process.env in node.js process.env APP_ENV NODE_ENV https://nodejs.org/api/proc ...
- JavaScript简明教程之Node.js
Node.js是目前非常火热的技术,但是它的诞生经历却很奇特. 众所周知,在Netscape设计出JavaScript后的短短几个月,JavaScript事实上已经是前端开发的唯一标准. 后来,微软通 ...
- node.js global object,util and so on
核心模块主要内容: 全局对象 常用工具 事件机制 文件系统访问 http服务器和客户端 global object: 所有的全局变量(除了global本身外)都是global object 的属性(a ...
- 使用Node.js完成的第一个项目的实践总结
http://blog.csdn.net/yanghua_kobe/article/details/17199417 项目简介 这是一个资产管理项目,主要的目的就是实现对资产的无纸化管理.通过为每个资 ...
- [转]Node.js tutorial in Visual Studio Code
本文转自:https://code.visualstudio.com/docs/nodejs/nodejs-tutorial Node.js tutorial in Visual Studio Cod ...
- Practical Node.js摘录(2018版)第1,2章。
大神的node书,免费 视频:https://node.university/courses/short-lectures/lectures/3949510 另一本书:全栈JavaScript,学习b ...
随机推荐
- LPC43xx SGPIO I2C Implementation
I²C SGPIO Configuration SGPIO is a hardware feature of LPC4300 series. There are 16 SGPIO pins calle ...
- Cortex-M4 Core Registers
Cortex-M4 Core Registers Goal: visualizing what happens to the Cortex-M4 core registers after reset ...
- J-Link Version
"J-Link / Flasher Portable V1 " "J-Link ARM / Flasher ARM V2 " "J-Link ARM ...
- STM32学习日志--使用DMA功能自动更新PWM的输出
/******************************************************************************* 编译环境: EWARM V5.30 硬 ...
- 导出文件在IE和火狐中文件名乱码问题的解决
$ua = $_SERVER["HTTP_USER_AGENT"]; $filename = "客户数据.xls"; $encoded_filename = u ...
- [Winform]Cefsharp重写alert与confirm弹窗
摘要 在使用winform内嵌cefsharp浏览本地页面的时候,如果出现alert弹窗,会在标题栏显示页面所在目录.所以想起来重写alert的样式,通过winform的MessageBox进行提示. ...
- file is universal (4 slices) but does not contain a(n) armv7s slice
关于ld: file is universal (2 slices) but does not contain a(n) armv7s slice 升级了xcode之后,支持iOS6和iPhone5, ...
- .Net中集合排序
public class StockQuantity { public StockQuantity(string status, DateTime dateTime, int quantity) { ...
- Linux学习9-CentOS搭建nginx环境
前言 之前我们搭建网站的时候,把war包放到tomcat下就能运行起来了,为什么部署上线的时候,又用到了nginx呢? nginx可以做多台服务器的负载均衡,当用户非常少的时候,可以用一台服务直接部署 ...
- jQuery - 同时添加click和dblclick事件
添加事件的代码比较简单,有两种方法: $("abc").bind({"click":fn,"dblclick":fn}); $(" ...