UI for Zipcoin Blue

index.js 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. };