promisify.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. var _ = require("./_");
  2. var isFn = _.isFunction;
  3. module.exports = function (fn, self) {
  4. return function (a, b, c, d, e) {
  5. var len = arguments.length
  6. , args, promise, resolve, reject;
  7. promise = new _.Promise(function (r, rj) {
  8. resolve = r;
  9. reject = rj;
  10. });
  11. function cb (err, val) {
  12. err == null ? resolve(val) : reject(err);
  13. }
  14. // For the sake of performance.
  15. switch (len) {
  16. case 0: fn.call(self, cb); break;
  17. case 1: isFn(a) ? fn.call(self, a) : fn.call(self, a, cb); break;
  18. case 2: isFn(b) ? fn.call(self, a, b) : fn.call(self, a, b, cb); break;
  19. case 3: isFn(c) ? fn.call(self, a, b, c) : fn.call(self, a, b, c, cb); break;
  20. case 4: isFn(d) ? fn.call(self, a, b, c, d) : fn.call(self, a, b, c, d, cb); break;
  21. case 5: isFn(e) ? fn.call(self, a, b, c, d, e) : fn.call(self, a, b, c, d, e, cb); break;
  22. default:
  23. args = new Array(len);
  24. for (var i = 0; i < len; i++) {
  25. args[i] = arguments[i];
  26. }
  27. if (isFn(args[len - 1])) {
  28. return fn.apply(self, args);
  29. }
  30. args[i] = cb;
  31. fn.apply(self, args);
  32. }
  33. return promise;
  34. };
  35. };