阿西河

所有教程

公众号
🌙
阿西河前端的公众号

我的收藏

    最近访问  (文章)

      教程列表

      抓包专区
      测试专区

      Node.js 自定义 promisify 函数

      Node.js 自定义 promisify 函数

      Using the util.promisify.custom symbol one can override the return value of

      const util = require('util');
      
      function doSomething(foo, callback) {
        // ...
      }
      
      doSomething[util.promisify.custom] = (foo) => {
        return getPromiseSomehow();
      };
      
      const promisified = util.promisify(doSomething);
      console.log(promisified === doSomething[util.promisify.custom]);
      // prints 'true'
      

      This can be useful for cases where the original function does not follow the standard format of taking an error-first callback as the last argument.

      For example, with a function that takes in (foo, onSuccessCallback, onErrorCallback):

      doSomething[util.promisify.custom] = (foo) => {
        return new Promise((resolve, reject) => {
          doSomething(foo, resolve, reject);
        });
      };
      

      If promisify.custom is defined but is not a function, promisify() will throw an error.


      更多内容请参考:Node.js util 实用工具,或者通过 点击对应菜单 进行查看;


      目录
      本文目录
      目录