前言
util工具类中的方法有很多,将陆续补充...。
一、require('util')
const util = require('util');
二、util.callbackify
Takes an
asyncfunction (or a function that returns aPromise) 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 (ornullif thePromiseresolved), 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
nullhas a special meaning as the first argument to a callback, if a wrapped function rejects aPromisewith a falsy value as a reason, the value is wrapped in anErrorwith the original value stored in a field namedreason回调函数是异步执行的,并且有异常堆栈错误追踪。 如果回调函数抛出一个异常,进程会触发一个 '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
});
本文介绍了如何使用Node.js内置util模块中的callbackify方法,将异步函数转换为接受错误优先回调的函数形式,同时讲解了Promise在回调中的特殊处理,包括null作为原因时的包装和错误传播机制。
890

被折叠的 条评论
为什么被折叠?



