promises.js 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. const { promisify, callbackify } = require('util')
  2. const pLimit = require('p-limit')
  3. module.exports = {
  4. promisify,
  5. promisifyAll,
  6. promisifyMultiResult,
  7. callbackify,
  8. callbackifyMultiResult,
  9. expressify,
  10. promiseMapWithLimit,
  11. }
  12. /**
  13. * Promisify all functions in a module.
  14. *
  15. * This is meant to be used only when all functions in the module are async
  16. * callback-style functions.
  17. *
  18. * It's very much tailored to our current module structure. In particular, it
  19. * binds `this` to the module when calling the function in order not to break
  20. * modules that call sibling functions using `this`.
  21. *
  22. * This will not magically fix all modules. Special cases should be promisified
  23. * manually.
  24. *
  25. * The second argument is a bag of options:
  26. *
  27. * - without: an array of function names that shouldn't be promisified
  28. *
  29. * - multiResult: an object whose keys are function names and values are lists
  30. * of parameter names. This is meant for functions that invoke their callbacks
  31. * with more than one result in separate parameters. The promisifed function
  32. * will return these results as a single object, with each result keyed under
  33. * the corresponding parameter name.
  34. */
  35. function promisifyAll(module, opts = {}) {
  36. const { without = [], multiResult = {} } = opts
  37. const promises = {}
  38. for (const propName of Object.getOwnPropertyNames(module)) {
  39. if (without.includes(propName)) {
  40. continue
  41. }
  42. const propValue = module[propName]
  43. if (typeof propValue !== 'function') {
  44. continue
  45. }
  46. if (multiResult[propName] != null) {
  47. promises[propName] = promisifyMultiResult(
  48. propValue,
  49. multiResult[propName]
  50. ).bind(module)
  51. } else {
  52. promises[propName] = promisify(propValue).bind(module)
  53. }
  54. }
  55. return promises
  56. }
  57. /**
  58. * Promisify a function that returns multiple results via additional callback
  59. * parameters.
  60. *
  61. * The promisified function returns the results in a single object whose keys
  62. * are the names given in the array `resultNames`.
  63. *
  64. * Example:
  65. *
  66. * function f(callback) {
  67. * return callback(null, 1, 2, 3)
  68. * }
  69. *
  70. * const g = promisifyMultiResult(f, ['a', 'b', 'c'])
  71. *
  72. * const result = await g() // returns {a: 1, b: 2, c: 3}
  73. */
  74. function promisifyMultiResult(fn, resultNames) {
  75. function promisified(...args) {
  76. return new Promise((resolve, reject) => {
  77. try {
  78. fn(...args, (err, ...results) => {
  79. if (err != null) {
  80. return reject(err)
  81. }
  82. const promiseResult = {}
  83. for (let i = 0; i < resultNames.length; i++) {
  84. promiseResult[resultNames[i]] = results[i]
  85. }
  86. resolve(promiseResult)
  87. })
  88. } catch (err) {
  89. reject(err)
  90. }
  91. })
  92. }
  93. return promisified
  94. }
  95. /**
  96. * Reverse the effect of `promisifyMultiResult`.
  97. *
  98. * This is meant for providing a temporary backward compatible callback
  99. * interface while we migrate to promises.
  100. */
  101. function callbackifyMultiResult(fn, resultNames) {
  102. function callbackified(...args) {
  103. const [callback] = args.splice(-1)
  104. fn(...args)
  105. .then(result => {
  106. const cbResults = resultNames.map(resultName => result[resultName])
  107. callback(null, ...cbResults)
  108. })
  109. .catch(err => {
  110. callback(err)
  111. })
  112. }
  113. return callbackified
  114. }
  115. /**
  116. * Transform an async function into an Express middleware
  117. *
  118. * Any error will be passed to the error middlewares via `next()`
  119. */
  120. function expressify(fn) {
  121. return (req, res, next) => {
  122. fn(req, res, next).catch(next)
  123. }
  124. }
  125. /**
  126. * Map values in `array` with the async function `fn`
  127. *
  128. * Limit the number of unresolved promises to `concurrency`.
  129. */
  130. function promiseMapWithLimit(concurrency, array, fn) {
  131. const limit = pLimit(concurrency)
  132. return Promise.all(array.map(x => limit(() => fn(x))))
  133. }