Node.js – util.callbackify() 方法
util.callbackify() 方法将异步函数(或带 Promise 的函数)作为参数,然后返回一个具有回调样式的函数。回调会将拒绝原因作为第一个参数(或在 Promise 的情况下为 null),并将已解析的值作为第二个参数保存。
语法
util.callbackify(function)
参数
- function − 异步函数 async_function 的输入参数,需要回调。
示例 1
创建一个名为 "callbackify.js" 的文件,并复制以下代码段。创建文件后,可以使用命令 "node callbackify.js" 来运行此代码。
// util.callbackify() demo example
// Importing the util module
const util = require('util');
// Defining a simple async function
async function async_fn() {
return 'Welcome to Turoials Point !!!';
}
// Defining the util.callbackify() with async function
const callbackFunction = util.callbackify(async_fn);
// Consuming the callback
callbackFunction((err, ret) => {
if (err) throw err;
console.log(ret);
});输出
C:\home
ode>> node callbackify.js Welcome to Turoials Point !!!
示例 2
如果在执行函数时发生任何错误或异常,回调将抛出一个“未捕获异常”事件。如果回调未处理,它将退出。让我们尝试将 callbackify() 函数与一个具有 null 参数的 Promise 一起使用。
// util.callbackify() demo example
// Importing the util module
const util = require('util');
// Defining a simple Promise function
function async_fn() {
return Promise.reject(null);
}
// Defining the callback function
const callbackFunction = util.callbackify(async_fn);
callbackFunction((err, ret) => {
// The promise will be rejected with 'null', as it is wrapped
// with an Error and the error message being stored in the 'reason'
err && err.hasOwnProperty('reason') && err.reason === null;
// true(since promise has error)
console.log(err);
});输出
C:\home
ode>> node callbackify.js { Error [ERR_FALSY_VALUE_REJECTION]: Promise was rejected with falsy value at process._tickCallback (internal/process/next_tick.js:63:19) at Function.Module.runMain (internal/modules/cjs/loader.js:834:11) at startup (internal/bootstrap/node.js:283:19) at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3) reason: null }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP