Node.js util工具类

本文介绍了如何使用Node.js内置util模块中的callbackify方法,将异步函数转换为接受错误优先回调的函数形式,同时讲解了Promise在回调中的特殊处理,包括null作为原因时的包装和错误传播机制。

前言

 util工具类中的方法有很多,将陆续补充...。


 

一、require('util')

const util = require('util');

二、util.callbackify

Takes an async function (or a function that returns a Promise) and returns a function following the error-first callback style, i.e. taking an (err, value) => ... callback as the last argument. In the callback, the first argument will be the rejection reason (or null if the Promise resolved), and the second argument will be the resolved value.

将 async 异步函数(或者一个返回值为 Promise 的函数)转换成遵循异常优先的回调风格的函数;第一个参数为拒绝的原因,第二个参数将是已解决的值.

 

const util = require('util');

async function fn() {
  return 'hello world';
}
const callbackFunction = util.callbackify(fn);

callbackFunction((err, ret) => {
  if (err) throw err;
  console.log(ret);
});

The callback is executed asynchronously, and will have a limited stack trace. If the callback throws, the process will emit an 'uncaughtException' event, and if not handled will exit.

Since null has a special meaning as the first argument to a callback, if a wrapped function rejects a Promise with a falsy value as a reason, the value is wrapped in an Error with the original value stored in a field named reason

 回调函数是异步执行的,并且有异常堆栈错误追踪。 如果回调函数抛出一个异常,进程会触发一个 'uncaughtException' 异常,如果没有被捕获,进程将会退出。

null 在回调函数中作为一个参数有其特殊的意义,如果回调函数的首个参数为 Promise 拒绝的原因且带有返回值,且值可以转换成布尔值 false,这个值会被封装在 Error 对象里,可以通过属性 reason 获取。

function fn() {
  return Promise.reject(null);
}
const callbackFunction = util.callbackify(fn);

callbackFunction((err, ret) => {
  // When the Promise was rejected with `null` it is wrapped with an Error and
  // the original value is stored in `reason`.
  err && err.hasOwnProperty('reason') && err.reason === null;  // true
});

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值