當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js util.callbackify()用法及代碼示例

util.callbackify()方法是util模塊的內置應用程序編程接口,用於運行異步函數並在node.js中獲取回調。

用法:

util.callbackify( async_function )

參數:該方法接受上述和以下描述的單個參數。



  • async_function:它是必需的參數,表示原始異步函數。

返回值:它以error-first回調樣式函數的形式返回Promise。它以(err,ret)=> {}作為參數,其第一個參數是錯誤或拒絕原因,可能為null(當promise被解決時),第二個參數是已解決的值。

以下示例說明了Node.js中util.callbackify()方法的使用:

範例1:

// Node.js program to demonstrate the    
// util.callbackify() Method  
  
// Allocating util module 
const util = require('util'); 
  
// Async function to be called 
// from util.callbackify() method 
async function async_function() { 
    return 'message from async function'; 
} 
  
// Calling callbackify() 
const callback_function =  
        util.callbackify(async_function); 
  
// Listner for callback_function 
callback_function((err, ret) => { 
    if (err) throw err; 
    console.log(ret); 
});

輸出:

message from async function

範例2:

// Node.js program to demonstrate the    
// util.callbackify() Method  
  
// Allocating util module 
const util = require('util'); 
  
// Async function to be called  
// from util.callbackify() method 
async function async_function() { 
    return Promise.reject(new Error( 
        'this is an error message!')); 
} 
  
// Calling callbackify() 
const callback_function = 
    util.callbackify(async_function); 
  
// Listner for callback_function 
callback_function((err, ret) => { 
  
    // If error occurs 
    if (err && err.hasOwnProperty('reason') 
        && err.reason === null) { 
  
        // Printing error reason 
        console.log(err.reason); 
    } else { 
        console.log(err); 
    } 
});

輸出:

Error:this is an error message!
    at async_function (C:\nodejs\g\util\callbackify_2.js:6:25)
    at async_function (util.js:356:13)
    at Object. (C:\nodejs\g\util\callbackify_2.js:12:1)
    at Module._compile (internal/modules/cjs/loader.js:776:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
    at startup (internal/bootstrap/node.js:283:19)

注意:上麵的程序將通過使用node filename.js命令。

參考: https://nodejs.org/api/util.html#util_util_callbackify_original




相關用法


注:本文由純淨天空篩選整理自gekcho大神的英文原創作品 Node.js | util.callbackify() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。