[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 ...
随机推荐
- Polly简介 — 3. 执行策略
执行策略 执行策略的常见方式是调用策略的Execute函数 var policy = Policy.Handle<TimeoutException>().Retry();policy.Ex ...
- Timer-triggered memory-to-memory DMA transfer demonstrator
http://www.efton.sk/STM32/bt.c // Timer-triggered memory-to-memory DMA transfer demonstrator for STM ...
- CRC校验的实现
本例提供的是通过查表发来实现CRC校验. CRC余式表如下: unsigned int crctab[256] ={/*CRC余式表 */ 0x0000, 0x1021, 0x2042, 0x3063 ...
- ICE概述
网络通信引擎(Internet Communications Engine, Ice)是由ZeroC的分布式系统开发专家实现的一种高性能.面向对象的中间件平台.它号称标准统一,开源,跨平台,跨语言,分 ...
- ASP.NET MVC中MaxLength特性设置无效
在ASP.NET MVC项目中,给某个Model打上了MaxLength特性如下: public class SomeClass { [MaxLength(16, ErrorMessage = &qu ...
- OpenLdap+MySQL笔记
20元现金领取地址:http://jdb.jiudingcapital.com/phone.html内部邀请码:C8E245J (不写邀请码,没有现金送) 国内私募机构九鼎控股打造,九鼎投资是在全国股 ...
- JPA & Hibernate 注解
1 . @Entity(name="EntityName") 必须 ,name 为可选 , 对应数据库中一的个表 2 . @Table(name="",cata ...
- 图标框架Font Awesome
直接引入Font Awesome的css <!DOCTYPE html> <html lang="en"> <head> <meta ch ...
- springMVC helloworld入门
一.SpringMVC概述与基本原理 spring Web MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将web层进行职责解耦 ...
- 美国恐怖故事第七季/全集American Horror Story全迅雷下载
FX电视台已经续订了<美国恐怖故事>第七季,将于2017年开播,第七季终于确定副标题为<邪教 Cult>.剧集的创造者瑞恩·墨菲与布拉德·法尔查克将再度联手.顺便一说,< ...