util.callbackify(original)


采用 async 函数(或返回 Promise 的函数)并返回遵循错误优先回调风格的函数,即将 (err, value) => ... 回调作为最后一个参数。 在回调中,第一个参数将是拒绝原因(如果 Promise 已解决,则为 null),第二个参数将是已解决的值。

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);
});

将打印:

hello world

回调是异步执行的,并且将具有有限的堆栈跟踪。 如果回调抛出,进程将触发 'uncaughtException' 事件,如果不处理将退出。

由于 null 作为回调的第一个参数有特殊含义,如果封装的函数使用假值为理由来拒绝 Promise,则该值被封装在 Error 中,原始值存储在名为 reason 的字段中。

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

callbackFunction((err, ret) => {
  // 当 Promise 使用 `null` 拒绝时,它会使用 Error 封装,
  // 原始值存储在 `reason` 中。
  err && err.hasOwnProperty('reason') && err.reason === null;  // true
});

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.

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);
});

Will print:

hello world

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.

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
});