实现bluebird的promiseify函数

'use strict';

const fs = require('fs');
const readFile = fs.readFile;

function promiseify(method){
  return function(ctx){
    let args = Array.prototype.slice.call(arguments);

    return new Promise((resolve, reject) => {
      let cb = function(err, result){
        if(err){
          return reject(err);
        }

        return resolve(result);
      }

      args.push(cb);
      method.apply(ctx, args);
    });
  };
}

let readFileAsync = promiseify(readFile);

readFileAsync('./promiseify.js')
.then((result) => {
  console.log(result.toString());
})
.catch((err) => {
  console.log(`error:${err}`);
});

你可能感兴趣的:(实现bluebird的promiseify函数)