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. Go 导入当前项目下的包

    其实和其他语言很类似 import (     "../controllers" //这里就是导入上一级目录中的controllers     "./models&quo ...

  2. 打印 Go 结构体(struct)信息:fmt.Printf("%+v", user)

    package main import "fmt" // 用户 type User struct { Id int Name string Age int } func main( ...

  3. SQL Server on Linux

    https://edu.aliyun.com/course/51/lesson/list?spm=5176.8764728.aliyun-edu-course-tab.2.4YyLGD&pre ...

  4. 图解tensorflow 源码分析

    http://www.cnblogs.com/yao62995/p/5773578.html https://github.com/yao62995/tensorflow

  5. 《大话设计模式》C#/C++版pdf/源码下载

    大话设计模式(带目录完整版)[中文PDF+源代码].zip 下载地址:http://pan.baidu.com/s/1giQP4大话设计模式C++.pdf下载地址:http://pan.baidu.c ...

  6. 国内打不开onedrive,怎么办?

    Onedrive不能正常连接使用是由于DNS遭到污染闹的,其上传和下载文件慢也是DNS遭到污染闹的. 方法/步骤   在C盘windows/system32/drivers/etc/hosts下,用记 ...

  7. 使用Axure RP原型设计实践04,了解全局变量

    变量是一个可以变的数,可以看作是一个数据的容器.变量有2个操作,一个是读,一个是写.Axure的全局变量是指任何时候都可以对这个变量进行读写操作. 点击工具栏Project下的Global Varia ...

  8. ASP.NET MVC中检测浏览器版本并提示下载更新

    如果网站使用html5.css3.自适应等新特性,可能有些浏览器版本不支持.这时候,需要提醒浏览者更新浏览器的版本到最新. 本篇用到的插件为:http://jreject.turnwheel.com/ ...

  9. Informix 常用函数

    一.内部函数 1.内部合计函数 1)COUNT(*) 返回行数 2)COUNT(DISTINCT COLNAME) 返回指定列中唯一值的个数 3)SUM(COLNAME/EXPRESSION) 返回指 ...

  10. spring post 图片

    @RequestMapping(value = "/post",method = RequestMethod.POST) @ResponseBody String GPost(@R ...