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的更多相关文章

  1. Node.js & process.env & OS Platform checker

    Node.js & process.env & OS Platform checker Window 10 Windows 7 ia32 CentOS $ node # process ...

  2. Node.js process 模块常用属性和方法

    Node.js是常用的Javascript运行环境,本文和大家发分享的主要是Node.js中process 模块的常用属性和方法,希望通过本文的分享,对大家学习Node.js http://www.m ...

  3. Node.js 101(2): Promise and async

    --原文地址:http://blog.chrisyip.im/nodejs-101-package-promise-and-async 先回想一下 Sagase 的项目结构: lib/ cli.js ...

  4. 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 ...

  5. JavaScript简明教程之Node.js

    Node.js是目前非常火热的技术,但是它的诞生经历却很奇特. 众所周知,在Netscape设计出JavaScript后的短短几个月,JavaScript事实上已经是前端开发的唯一标准. 后来,微软通 ...

  6. node.js global object,util and so on

    核心模块主要内容: 全局对象 常用工具 事件机制 文件系统访问 http服务器和客户端 global object: 所有的全局变量(除了global本身外)都是global object 的属性(a ...

  7. 使用Node.js完成的第一个项目的实践总结

    http://blog.csdn.net/yanghua_kobe/article/details/17199417 项目简介 这是一个资产管理项目,主要的目的就是实现对资产的无纸化管理.通过为每个资 ...

  8. [转]Node.js tutorial in Visual Studio Code

    本文转自:https://code.visualstudio.com/docs/nodejs/nodejs-tutorial Node.js tutorial in Visual Studio Cod ...

  9. Practical Node.js摘录(2018版)第1,2章。

    大神的node书,免费 视频:https://node.university/courses/short-lectures/lectures/3949510 另一本书:全栈JavaScript,学习b ...

随机推荐

  1. 关于MongoDB时区问题

    由于MongoDb存储时间按照UTC时间存储的,其官方驱动MongoDB.driver存储时间的时候将本地时间转换为了utc时间,但它有个蛋疼的bug,读取的时候非常蛋疼的是返回的是utc使时间.一个 ...

  2. An Isolated DAC Using PWM Output

    An Isolated DAC Using PWM Output Arduino‘s (ATmega328P) PWM outputs via analogWrite can be convenien ...

  3. STM32F4 -- How to use the DMA burst feature

    Bits 15:13 Reserved, must be kept at reset value. Bits 12:8 DBL[4:0]: DMA burst length This 5-bit ve ...

  4. Timer triggered DMA transfer - Delay between requesting the DMA transfer

    Hello, I'm working with a STM32F407 controller board.   Right now, I want to trigger a DMA transfer ...

  5. STM32F4, USB HS with ULPI and Suspend/Wakeup

    Hi guys,I am in need of your help, unfortunately STs documentation is lacking some information here. ...

  6. 突破 BTrace 安全限制

    http://blog.csdn.net/alivetime/article/details/6548615

  7. 浅谈BFC和IFC

    先说说FC,FC的含义就是Fomatting Context.它是CSS2.1规范中的一个概念. 它是页面中的一块渲染区域.而且有一套渲染规则,它决定了其子元素将怎样定位.以及和其它元素的关系和相互作 ...

  8. [Winform]只允许运行一个exe,如果已运行则将窗口置前

    摘要 接着介绍项目中用到的一些方法,在winform中,打好包,有时并不允许运行多个客户端,要保证只有一个客户端运行.如果已经运行了,则弹出已运行的窗口,使其展示. 方法 判断是否有相同的进程 /// ...

  9. 在ASP.NET Web API中使用OData的单例模式

    从OData v4开始增加了对单例模式的支持,我们不用每次根据主键等来获取某个EDM,就像在C#中使用单例模式一样.实现方式大致需要两步: 1.在需要实现单例模式的导航属性上加上[Singleton] ...

  10. 微信破解,解密?How To Decrypt WeChat EnMicroMsg.db Database?

    20元现金领取地址:http://jdb.jiudingcapital.com/phone.html内部邀请码:C8E245J (不写邀请码,没有现金送) 国内私募机构九鼎控股打造,九鼎投资是在全国股 ...