UNPKG

1.34 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6
7var _typeof2 = require('babel-runtime/helpers/typeof');
8
9var _typeof3 = _interopRequireDefault(_typeof2);
10
11var _once = require('once');
12
13var _once2 = _interopRequireDefault(_once);
14
15function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
16
17// takes a function or a flat value and returns the resolved value to the callback
18// if a fn, it must return a flat value, a promise, or pass something to a callback
19var handleAsync = function handleAsync(fn, cb) {
20 // flat value
21 if (typeof fn !== 'function') return cb(null, fn);
22
23 var wrapped = (0, _once2.default)(cb);
24
25 // call fn w callback
26 var res = void 0;
27 try {
28 res = fn(wrapped);
29 } catch (err) {
30 return wrapped(err);
31 }
32
33 // using a callback, itll call with a response
34 if (typeof res === 'undefined') return;
35
36 // using a promise
37 if (res != null && (typeof res === 'undefined' ? 'undefined' : (0, _typeof3.default)(res)) === 'object' && typeof res.then === 'function') {
38 res.then(function (data) {
39 wrapped(null, data);
40 return null;
41 }).catch(function (err) {
42 wrapped(err);
43 });
44 return;
45 }
46
47 // returned a plain value
48 wrapped(null, res);
49};
50
51exports.default = handleAsync;
52module.exports = exports['default'];
\No newline at end of file