promiseUtils.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. const Promise = require('bluebird');
  2. const { isObject } = require('./objectUtils');
  3. function isPromise(obj) {
  4. return isObject(obj) && typeof obj.then === 'function';
  5. }
  6. // Call `func` after `obj` has been resolved. Call `func` synchronously if
  7. // `obj` is not a promise for performance reasons.
  8. function after(obj, func) {
  9. if (isPromise(obj)) {
  10. return obj.then(func);
  11. } else {
  12. return func(obj);
  13. }
  14. }
  15. // Return `returnValue` after `obj` has been resolved. Return `returnValue`
  16. // synchronously if `obj` is not a promise for performance reasons.
  17. function afterReturn(obj, returnValue) {
  18. if (isPromise(obj)) {
  19. return obj.then(() => returnValue);
  20. } else {
  21. return returnValue;
  22. }
  23. }
  24. // Map `arr` with `mapper` and after that return `returnValue`. If none of
  25. // the mapped values is a promise, return synchronously for performance
  26. // reasons.
  27. function mapAfterAllReturn(arr, mapper, returnValue) {
  28. const results = new Array(arr.length);
  29. let containsPromise = false;
  30. for (let i = 0, l = arr.length; i < l; ++i) {
  31. results[i] = mapper(arr[i]);
  32. if (isPromise(results[i])) {
  33. containsPromise = true;
  34. }
  35. }
  36. if (containsPromise) {
  37. return Promise.all(results).return(returnValue);
  38. } else {
  39. return returnValue;
  40. }
  41. }
  42. module.exports = {
  43. isPromise,
  44. after,
  45. afterReturn,
  46. mapAfterAllReturn
  47. };