Ohm-Management - Projektarbeit B-ME
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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. 'use strict';
  2. var isPromise = require('is-promise');
  3. /**
  4. * Return a function that will run a function asynchronously or synchronously
  5. *
  6. * example:
  7. * runAsync(wrappedFunction, callback)(...args);
  8. *
  9. * @param {Function} func Function to run
  10. * @param {Function} cb Callback function passed the `func` returned value
  11. * @return {Function(arguments)} Arguments to pass to `func`. This function will in turn
  12. * return a Promise (Node >= 0.12) or call the callbacks.
  13. */
  14. var runAsync = module.exports = function (func, cb) {
  15. cb = cb || function () {};
  16. return function () {
  17. var async = false;
  18. var args = arguments;
  19. var promise = new Promise(function (resolve, reject) {
  20. var answer = func.apply({
  21. async: function () {
  22. async = true;
  23. return function (err, value) {
  24. if (err) {
  25. reject(err);
  26. } else {
  27. resolve(value);
  28. }
  29. };
  30. }
  31. }, Array.prototype.slice.call(args));
  32. if (!async) {
  33. if (isPromise(answer)) {
  34. answer.then(resolve, reject);
  35. } else {
  36. resolve(answer);
  37. }
  38. }
  39. });
  40. promise.then(cb.bind(null, null), cb);
  41. return promise;
  42. }
  43. };
  44. runAsync.cb = function (func, cb) {
  45. return runAsync(function () {
  46. var args = Array.prototype.slice.call(arguments);
  47. if (args.length === func.length - 1) {
  48. args.push(this.async());
  49. }
  50. return func.apply(this, args);
  51. }, cb);
  52. };