暫無描述
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. "use strict";
  2. module.exports = asPromise;
  3. /**
  4. * Callback as used by {@link util.asPromise}.
  5. * @typedef asPromiseCallback
  6. * @type {function}
  7. * @param {Error|null} error Error, if any
  8. * @param {...*} params Additional arguments
  9. * @returns {undefined}
  10. */
  11. /**
  12. * Returns a promise from a node-style callback function.
  13. * @memberof util
  14. * @param {asPromiseCallback} fn Function to call
  15. * @param {*} ctx Function context
  16. * @param {...*} params Function arguments
  17. * @returns {Promise<*>} Promisified function
  18. */
  19. function asPromise(fn, ctx/*, varargs */) {
  20. var params = new Array(arguments.length - 1),
  21. offset = 0,
  22. index = 2,
  23. pending = true;
  24. while (index < arguments.length)
  25. params[offset++] = arguments[index++];
  26. return new Promise(function executor(resolve, reject) {
  27. params[offset] = function callback(err/*, varargs */) {
  28. if (pending) {
  29. pending = false;
  30. if (err)
  31. reject(err);
  32. else {
  33. var params = new Array(arguments.length - 1),
  34. offset = 0;
  35. while (offset < params.length)
  36. params[offset++] = arguments[offset];
  37. resolve.apply(null, params);
  38. }
  39. }
  40. };
  41. try {
  42. fn.apply(ctx || null, params);
  43. } catch (err) {
  44. if (pending) {
  45. pending = false;
  46. reject(err);
  47. }
  48. }
  49. });
  50. }