root / HServer / 00.Server / 00.Program / node_modules / async / ensureAsync.js
이력 | 보기 | 이력해설 | 다운로드 (2.21 KB)
1 |
'use strict';
|
---|---|
2 |
|
3 |
Object.defineProperty(exports, "__esModule", {
|
4 |
value: true |
5 |
}); |
6 |
exports.default = ensureAsync;
|
7 |
|
8 |
var _setImmediate = require('./internal/setImmediate'); |
9 |
|
10 |
var _setImmediate2 = _interopRequireDefault(_setImmediate);
|
11 |
|
12 |
var _initialParams = require('./internal/initialParams'); |
13 |
|
14 |
var _initialParams2 = _interopRequireDefault(_initialParams);
|
15 |
|
16 |
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } |
17 |
|
18 |
/**
|
19 |
* Wrap an async function and ensure it calls its callback on a later tick of
|
20 |
* the event loop. If the function already calls its callback on a next tick,
|
21 |
* no extra deferral is added. This is useful for preventing stack overflows
|
22 |
* (`RangeError: Maximum call stack size exceeded`) and generally keeping
|
23 |
* [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony)
|
24 |
* contained.
|
25 |
*
|
26 |
* @name ensureAsync
|
27 |
* @static
|
28 |
* @memberOf module:Utils
|
29 |
* @method
|
30 |
* @category Util
|
31 |
* @param {Function} fn - an async function, one that expects a node-style
|
32 |
* callback as its last argument.
|
33 |
* @returns {Function} Returns a wrapped function with the exact same call
|
34 |
* signature as the function passed in.
|
35 |
* @example
|
36 |
*
|
37 |
* function sometimesAsync(arg, callback) {
|
38 |
* if (cache[arg]) {
|
39 |
* return callback(null, cache[arg]); // this would be synchronous!!
|
40 |
* } else {
|
41 |
* doSomeIO(arg, callback); // this IO would be asynchronous
|
42 |
* }
|
43 |
* }
|
44 |
*
|
45 |
* // this has a risk of stack overflows if many results are cached in a row
|
46 |
* async.mapSeries(args, sometimesAsync, done);
|
47 |
*
|
48 |
* // this will defer sometimesAsync's callback if necessary,
|
49 |
* // preventing stack overflows
|
50 |
* async.mapSeries(args, async.ensureAsync(sometimesAsync), done);
|
51 |
*/
|
52 |
function ensureAsync(fn) { |
53 |
return (0, _initialParams2.default)(function (args, callback) { |
54 |
var sync = true; |
55 |
args.push(function () {
|
56 |
var innerArgs = arguments; |
57 |
if (sync) {
|
58 |
(0, _setImmediate2.default)(function () { |
59 |
callback.apply(null, innerArgs);
|
60 |
}); |
61 |
} else {
|
62 |
callback.apply(null, innerArgs);
|
63 |
} |
64 |
}); |
65 |
fn.apply(this, args);
|
66 |
sync = false;
|
67 |
}); |
68 |
} |
69 |
module.exports = exports['default'];
|