Skip to content

Commit

Permalink
docs for ensureAsync
Browse files Browse the repository at this point in the history
  • Loading branch information
Alexander Early committed May 25, 2015
1 parent 219b4fb commit aba3e0c
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 15 deletions.
36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ Usage:

* [`memoize`](#memoize)
* [`unmemoize`](#unmemoize)
* [`ensureAsync`](#ensureAsync)
* [`log`](#log)
* [`dir`](#dir)
* [`noConflict`](#noConflict)
Expand Down Expand Up @@ -1657,6 +1658,41 @@ __Arguments__

* `fn` - the memoized function

---------------------------------------

<a name="ensureAsync" />
### ensureAsync(fn)

Wrap an async function and ensure it calls its callback on a later tick of the event loop. If the function already calls its callback on a next tick, no extra deferral is added. This is useful for preventing stack overflows (`RangeError: Maximum call stack size exceeded`) and generally keeping [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) contained.

__Arguments__

* `fn` - an async function, one that expects a node-style callback as its last argument

Returns a wrapped function with the exact same call signature as the function passed in.

__Example__

```js
function sometimesAsync(arg, callback) {
if (cache[arg]) {
return callback(null, cache[arg]); // this would be synchronous!!
} else {
doSomeIO(arg, callback); // this IO would be asynchronous
}
}

// this has a risk of stack overflows if many results are cached in a row
async.mapSeries(args, sometimesAsync, done);

// this will defer sometimesAsync's callback if necessary,
// preventing stack overflows
async.mapSeries(args, async.ensureAsync(sometimesAsync), done);

```

---------------------------------------

<a name="log" />
### log(function, arguments)

Expand Down
30 changes: 15 additions & 15 deletions lib/async.js
Original file line number Diff line number Diff line change
Expand Up @@ -1267,21 +1267,6 @@
next();
};

// Node.js
if (typeof module !== 'undefined' && module.exports) {
module.exports = async;
}
// AMD / RequireJS
else if (typeof define !== 'undefined' && define.amd) {
define([], function () {
return async;
});
}
// included directly via <script> tag
else {
root.async = async;
}

function ensureAsync(fn) {
return function (/*...args, callback*/) {
var args = _baseSlice(arguments);
Expand All @@ -1304,4 +1289,19 @@

async.ensureAsync = ensureAsync;

// Node.js
if (typeof module !== 'undefined' && module.exports) {
module.exports = async;
}
// AMD / RequireJS
else if (typeof define !== 'undefined' && define.amd) {
define([], function () {
return async;
});
}
// included directly via <script> tag
else {
root.async = async;
}

}());

0 comments on commit aba3e0c

Please sign in to comment.