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 }

更新於: 2021 年 8 月 16 日

484 次瀏覽

啟動你的 職業生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.