README.md 59,4 ko
Newer Older
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
function mySecondFunction(arg1, arg2, callback) {
  // arg1 now equals 'one' and arg2 now equals 'two'
  callback(null, 'three');
}
function myLastFunction(arg1, callback) {
  // arg1 now equals 'three'
  callback(null, 'done');
}
```

Or, if you need to pass any argument to the first function:

```js
async.waterfall([
    async.apply(myFirstFunction, 'zero'),
    mySecondFunction,
    myLastFunction,
], function (err, result) {
    // result now equals 'done'
});
function myFirstFunction(arg1, callback) {
  // arg1 now equals 'zero'
  callback(null, 'one', 'two');
}
function mySecondFunction(arg1, arg2, callback) {
  // arg1 now equals 'one' and arg2 now equals 'two'
  callback(null, 'three');
}
function myLastFunction(arg1, callback) {
  // arg1 now equals 'three'
  callback(null, 'done');
}
```

---------------------------------------
<a name="compose" />
### compose(fn1, fn2...)

Creates a function which is a composition of the passed asynchronous
functions. Each function consumes the return value of the function that
follows. Composing functions `f()`, `g()`, and `h()` would produce the result of
`f(g(h()))`, only this version uses callbacks to obtain the return values.

Each function is executed with the `this` binding of the composed function.

__Arguments__

* `functions...` - the asynchronous functions to compose


__Example__

```js
function add1(n, callback) {
    setTimeout(function () {
        callback(null, n + 1);
    }, 10);
}

function mul3(n, callback) {
    setTimeout(function () {
        callback(null, n * 3);
    }, 10);
}

var add1mul3 = async.compose(mul3, add1);

add1mul3(4, function (err, result) {
   // result now equals 15
});
```

---------------------------------------
<a name="seq" />
### seq(fn1, fn2...)

Version of the compose function that is more natural to read.
Each function consumes the return value of the previous function.
It is the equivalent of [`compose`](#compose) with the arguments reversed.

Each function is executed with the `this` binding of the composed function.

__Arguments__

* `functions...` - the asynchronous functions to compose


__Example__

```js
// Requires lodash (or underscore), express3 and dresende's orm2.
// Part of an app, that fetches cats of the logged user.
// This example uses `seq` function to avoid overnesting and error
// handling clutter.
app.get('/cats', function(request, response) {
  var User = request.models.User;
  async.seq(
    _.bind(User.get, User),  // 'User.get' has signature (id, callback(err, data))
    function(user, fn) {
      user.getCats(fn);      // 'getCats' has signature (callback(err, data))
    }
  )(req.session.user_id, function (err, cats) {
    if (err) {
      console.error(err);
      response.json({ status: 'error', message: err.message });
    } else {
      response.json({ status: 'ok', message: 'Cats found', data: cats });
    }
  });
});
```

---------------------------------------
<a name="applyEach" />
### applyEach(fns, args..., callback)

Applies the provided arguments to each function in the array, calling
`callback` after all functions have completed. If you only provide the first
argument, then it will return a function which lets you pass in the
arguments as if it were a single function call.

__Arguments__

* `fns` - the asynchronous functions to all call with the same arguments
* `args...` - any number of separate arguments to pass to the function
* `callback` - the final argument should be the callback, called when all
  functions have completed processing


__Example__

```js
async.applyEach([enableSearch, updateSchema], 'bucket', callback);

// partial application example:
async.each(
    buckets,
    async.applyEach([enableSearch, updateSchema]),
    callback
);
```

__Related__

* applyEachSeries(tasks, args..., [callback])

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

<a name="queue" />
### queue(worker, [concurrency])

Creates a `queue` object with the specified `concurrency`. Tasks added to the
`queue` are processed in parallel (up to the `concurrency` limit). If all
`worker`s are in progress, the task is queued until one becomes available.
Once a `worker` completes a `task`, that `task`'s callback is called.

__Arguments__

* `worker(task, callback)` - An asynchronous function for processing a queued
  task, which must call its `callback(err)` argument when finished, with an
  optional `error` as an argument.  If you want to handle errors from an individual task, pass a callback to `q.push()`.
* `concurrency` - An `integer` for determining how many `worker` functions should be
  run in parallel.  If omitted, the concurrency defaults to `1`.  If the concurrency is `0`, an error is thrown.

__Queue objects__

The `queue` object returned by this function has the following properties and
methods:

* `length()` - a function returning the number of items waiting to be processed.
* `started` - a function returning whether or not any items have been pushed and processed by the queue
* `running()` - a function returning the number of items currently being processed.
* `workersList()` - a function returning the array of items currently being processed.
* `idle()` - a function returning false if there are items waiting or being processed, or true if not.
* `concurrency` - an integer for determining how many `worker` functions should be
  run in parallel. This property can be changed after a `queue` is created to
  alter the concurrency on-the-fly.
* `push(task, [callback])` - add a new task to the `queue`. Calls `callback` once
  the `worker` has finished processing the task. Instead of a single task, a `tasks` array
  can be submitted. The respective callback is used for every task in the list.
* `unshift(task, [callback])` - add a new task to the front of the `queue`.
* `saturated` - a callback that is called when the `queue` length hits the `concurrency` limit,
   and further tasks will be queued.
* `empty` - a callback that is called when the last item from the `queue` is given to a `worker`.
* `drain` - a callback that is called when the last item from the `queue` has returned from the `worker`.
* `paused` - a boolean for determining whether the queue is in a paused state
* `pause()` - a function that pauses the processing of tasks until `resume()` is called.
* `resume()` - a function that resumes the processing of queued tasks when the queue is paused.
* `kill()` - a function that removes the `drain` callback and empties remaining tasks from the queue forcing it to go idle.

__Example__

```js
// create a queue object with concurrency 2

var q = async.queue(function (task, callback) {
    console.log('hello ' + task.name);
    callback();
}, 2);


// assign a callback
q.drain = function() {
    console.log('all items have been processed');
}

// add some items to the queue

q.push({name: 'foo'}, function (err) {
    console.log('finished processing foo');
});
q.push({name: 'bar'}, function (err) {
    console.log('finished processing bar');
});

// add some items to the queue (batch-wise)

q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) {
    console.log('finished processing item');
});

// add some items to the front of the queue

q.unshift({name: 'bar'}, function (err) {
    console.log('finished processing bar');
});
```


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

<a name="priorityQueue" />
### priorityQueue(worker, concurrency)

The same as [`queue`](#queue) only tasks are assigned a priority and completed in ascending priority order. There are two differences between `queue` and `priorityQueue` objects:

* `push(task, priority, [callback])` - `priority` should be a number. If an array of
  `tasks` is given, all tasks will be assigned the same priority.
* The `unshift` method was removed.

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

<a name="cargo" />
### cargo(worker, [payload])

Creates a `cargo` object with the specified payload. Tasks added to the
cargo will be processed altogether (up to the `payload` limit). If the
`worker` is in progress, the task is queued until it becomes available. Once
the `worker` has completed some tasks, each callback of those tasks is called.
Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) for how `cargo` and `queue` work.

While [queue](#queue) passes only one task to one of a group of workers
at a time, cargo passes an array of tasks to a single worker, repeating
when the worker is finished.

__Arguments__

* `worker(tasks, callback)` - An asynchronous function for processing an array of
  queued tasks, which must call its `callback(err)` argument when finished, with
  an optional `err` argument.
* `payload` - An optional `integer` for determining how many tasks should be
  processed per round; if omitted, the default is unlimited.

__Cargo objects__

The `cargo` object returned by this function has the following properties and
methods:

* `length()` - A function returning the number of items waiting to be processed.
* `payload` - An `integer` for determining how many tasks should be
  process per round. This property can be changed after a `cargo` is created to
  alter the payload on-the-fly.
* `push(task, [callback])` - Adds `task` to the `queue`. The callback is called
  once the `worker` has finished processing the task. Instead of a single task, an array of `tasks`
  can be submitted. The respective callback is used for every task in the list.
* `saturated` - A callback that is called when the `queue.length()` hits the concurrency and further tasks will be queued.
* `empty` - A callback that is called when the last item from the `queue` is given to a `worker`.
* `drain` - A callback that is called when the last item from the `queue` has returned from the `worker`.
* `idle()`, `pause()`, `resume()`, `kill()` - cargo inherits all of the same methods and event calbacks as [`queue`](#queue)

__Example__

```js
// create a cargo object with payload 2

var cargo = async.cargo(function (tasks, callback) {
    for(var i=0; i<tasks.length; i++){
      console.log('hello ' + tasks[i].name);
    }
    callback();
}, 2);


// add some items

cargo.push({name: 'foo'}, function (err) {
    console.log('finished processing foo');
});
cargo.push({name: 'bar'}, function (err) {
    console.log('finished processing bar');
});
cargo.push({name: 'baz'}, function (err) {
    console.log('finished processing baz');
});
```

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

<a name="auto" />
### auto(tasks, [concurrency], [callback])

Determines the best order for running the functions in `tasks`, based on their requirements. Each function can optionally depend on other functions being completed first, and each function is run as soon as its requirements are satisfied.

If any of the functions pass an error to their callback, the `auto` sequence will stop. Further tasks will not execute (so any other functions depending on it will not run), and the main `callback` is immediately called with the error.  Functions also receive an object containing the results of functions which have completed so far.

Note, all functions are called with a `results` object as a second argument,
so it is unsafe to pass functions in the `tasks` object which cannot handle the
extra argument.

For example, this snippet of code:

```js
async.auto({
  readData: async.apply(fs.readFile, 'data.txt', 'utf-8')
}, callback);
```

will have the effect of calling `readFile` with the results object as the last
argument, which will fail:

```js
fs.readFile('data.txt', 'utf-8', cb, {});
```

Instead, wrap the call to `readFile` in a function which does not forward the
`results` object:

```js
async.auto({
  readData: function(cb, results){
    fs.readFile('data.txt', 'utf-8', cb);
  }
}, callback);
```

__Arguments__

* `tasks` - An object. Each of its properties is either a function or an array of
  requirements, with the function itself the last item in the array. The object's key
  of a property serves as the name of the task defined by that property,
  i.e. can be used when specifying requirements for other tasks.
  The function receives two arguments: (1) a `callback(err, result)` which must be
  called when finished, passing an `error` (which can be `null`) and the result of
  the function's execution, and (2) a `results` object, containing the results of
  the previously executed functions.
* `concurrency` - An optional `integer` for determining the maximum number of tasks that can be run in parallel. By default, as many as possible.
* `callback(err, results)` - An optional callback which is called when all the
  tasks have been completed. It receives the `err` argument if any `tasks`
  pass an error to their callback. Results are always returned; however, if
  an error occurs, no further `tasks` will be performed, and the results
  object will only contain partial results.


__Example__

```js
async.auto({
    get_data: function(callback){
        console.log('in get_data');
        // async code to get some data
        callback(null, 'data', 'converted to array');
    },
    make_folder: function(callback){
        console.log('in make_folder');
        // async code to create a directory to store a file in
        // this is run at the same time as getting the data
        callback(null, 'folder');
    },
    write_file: ['get_data', 'make_folder', function(callback, results){
        console.log('in write_file', JSON.stringify(results));
        // once there is some data and the directory exists,
        // write the data to a file in the directory
        callback(null, 'filename');
    }],
    email_link: ['write_file', function(callback, results){
        console.log('in email_link', JSON.stringify(results));
        // once the file is written let's email a link to it...
        // results.write_file contains the filename returned by write_file.
        callback(null, {'file':results.write_file, 'email':'user@example.com'});
    }]
}, function(err, results) {
    console.log('err = ', err);
    console.log('results = ', results);
});
```

This is a fairly trivial example, but to do this using the basic parallel and
series functions would look like this:

```js
async.parallel([
    function(callback){
        console.log('in get_data');
        // async code to get some data
        callback(null, 'data', 'converted to array');
    },
    function(callback){
        console.log('in make_folder');
        // async code to create a directory to store a file in
        // this is run at the same time as getting the data
        callback(null, 'folder');
    }
],
function(err, results){
    async.series([
        function(callback){
            console.log('in write_file', JSON.stringify(results));
            // once there is some data and the directory exists,
            // write the data to a file in the directory
            results.push('filename');
            callback(null);
        },
        function(callback){
            console.log('in email_link', JSON.stringify(results));
            // once the file is written let's email a link to it...
            callback(null, {'file':results.pop(), 'email':'user@example.com'});
        }
    ]);
});
```

For a complicated series of `async` tasks, using the [`auto`](#auto) function makes adding
new tasks much easier (and the code more readable).


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

<a name="retry" />
### retry([opts = {times: 5, interval: 0}| 5], task, [callback])

Attempts to get a successful response from `task` no more than `times` times before
returning an error. If the task is successful, the `callback` will be passed the result
of the successful task. If all attempts fail, the callback will be passed the error and
result (if any) of the final attempt.

__Arguments__

* `opts` - Can be either an object with `times` and `interval` or a number.
  * `times` - The number of attempts to make before giving up.  The default is `5`.
  * `interval` - The time to wait between retries, in milliseconds.  The default is `0`.
  * If `opts` is a number, the number specifies the number of times to retry, with the default interval of `0`. 
* `task(callback, results)` - A function which receives two arguments: (1) a `callback(err, result)`
  which must be called when finished, passing `err` (which can be `null`) and the `result` of
  the function's execution, and (2) a `results` object, containing the results of
  the previously executed functions (if nested inside another control flow).
* `callback(err, results)` - An optional callback which is called when the
  task has succeeded, or after the final failed attempt. It receives the `err` and `result` arguments of the last attempt at completing the `task`.

The [`retry`](#retry) function can be used as a stand-alone control flow by passing a callback, as shown below:

```js
// try calling apiMethod 3 times
async.retry(3, apiMethod, function(err, result) {
    // do something with the result
});
```

```js
// try calling apiMethod 3 times, waiting 200 ms between each retry 
async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {
    // do something with the result
});
```

```js
// try calling apiMethod the default 5 times no delay between each retry 
async.retry(apiMethod, function(err, result) {
    // do something with the result
});
```

It can also be embedded within other control flow functions to retry individual methods
that are not as reliable, like this:

```js
async.auto({
    users: api.getUsers.bind(api),
    payments: async.retry(3, api.getPayments.bind(api))
}, function(err, results) {
  // do something with the results
});
```


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

<a name="iterator" />
### iterator(tasks)

Creates an iterator function which calls the next function in the `tasks` array,
returning a continuation to call the next one after that. It's also possible to
“peek” at the next iterator with `iterator.next()`.

This function is used internally by the `async` module, but can be useful when
you want to manually control the flow of functions in series.

__Arguments__

* `tasks` - An array of functions to run.

__Example__

```js
var iterator = async.iterator([
    function(){ sys.p('one'); },
    function(){ sys.p('two'); },
    function(){ sys.p('three'); }
]);

node> var iterator2 = iterator();
'one'
node> var iterator3 = iterator2();
'two'
node> iterator3();
'three'
node> var nextfn = iterator2.next();
node> nextfn();
'three'
```

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

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

Creates a continuation function with some arguments already applied.

Useful as a shorthand when combined with other control flow functions. Any arguments
passed to the returned function are added to the arguments originally passed
to apply.

__Arguments__

* `function` - The function you want to eventually apply all arguments to.
* `arguments...` - Any number of arguments to automatically apply when the
  continuation is called.

__Example__

```js
// using apply

async.parallel([
    async.apply(fs.writeFile, 'testfile1', 'test1'),
    async.apply(fs.writeFile, 'testfile2', 'test2'),
]);


// the same process without using apply

async.parallel([
    function(callback){
        fs.writeFile('testfile1', 'test1', callback);
    },
    function(callback){
        fs.writeFile('testfile2', 'test2', callback);
    }
]);
```

It's possible to pass any number of additional arguments when calling the
continuation:

```js
node> var fn = async.apply(sys.puts, 'one');
node> fn('two', 'three');
one
two
three
```

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

<a name="nextTick" />
### nextTick(callback), setImmediate(callback)

Calls `callback` on a later loop around the event loop. In Node.js this just
calls `process.nextTick`; in the browser it falls back to `setImmediate(callback)`
if available, otherwise `setTimeout(callback, 0)`, which means other higher priority
events may precede the execution of `callback`.

This is used internally for browser-compatibility purposes.

__Arguments__

* `callback` - The function to call on a later loop around the event loop.

__Example__

```js
var call_order = [];
async.nextTick(function(){
    call_order.push('two');
    // call_order now equals ['one','two']
});
call_order.push('one')
```

<a name="times" />
### times(n, iterator, [callback])

Calls the `iterator` function `n` times, and accumulates results in the same manner
you would use with [`map`](#map).

__Arguments__

* `n` - The number of times to run the function.
* `iterator` - The function to call `n` times.
* `callback` - see [`map`](#map)

__Example__

```js
// Pretend this is some complicated async factory
var createUser = function(id, callback) {
  callback(null, {
    id: 'user' + id
  })
}
// generate 5 users
async.times(5, function(n, next){
    createUser(n, function(err, user) {
      next(err, user)
    })
}, function(err, users) {
  // we should now have 5 users
});
```

__Related__

* timesSeries(n, iterator, [callback])
* timesLimit(n, limit, iterator, [callback])


## Utils

<a name="memoize" />
### memoize(fn, [hasher])

Caches the results of an `async` function. When creating a hash to store function
results against, the callback is omitted from the hash and an optional hash
function can be used.

If no hash function is specified, the first argument is used as a hash key, which may work reasonably if it is a string or a data type that converts to a distinct string. Note that objects and arrays will not behave reasonably. Neither will cases where the other arguments are significant. In such cases, specify your own hash function.

The cache of results is exposed as the `memo` property of the function returned
by `memoize`.

__Arguments__

* `fn` - The function to proxy and cache results from.
* `hasher` - An optional function for generating a custom hash for storing
  results. It has all the arguments applied to it apart from the callback, and
  must be synchronous.

__Example__

```js
var slow_fn = function (name, callback) {
    // do something
    callback(null, result);
};
var fn = async.memoize(slow_fn);

// fn can now be used as if it were slow_fn
fn('some name', function () {
    // callback
});
```

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

Undoes a [`memoize`](#memoize)d function, reverting it to the original, unmemoized
form. Handy for testing.

__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="constant">
### constant(values...)

Returns a function that when called, calls-back with the values provided.  Useful as the first function in a `waterfall`, or for plugging values in to `auto`.

__Example__

```js
async.waterfall([
  async.constant(42),
  function (value, next) {
    // value === 42
  },
  //...
], callback);

async.waterfall([
  async.constant(filename, "utf8"),
  fs.readFile,
  function (fileData, next) {
    //...
  }
  //...
], callback);

async.auto({
  hostname: async.constant("https://server.net/"),
  port: findFreePort,
  launchServer: ["hostname", "port", function (cb, options) {
    startServer(options, cb);
  }],
  //...
}, callback);

```

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

<a name="asyncify">
<a name="wrapSync">
### asyncify(func)

__Alias:__ `wrapSync`

Take a sync function and make it async, passing its return value to a callback. This is useful for plugging sync functions into a waterfall, series, or other async functions. Any arguments passed to the generated function will be passed to the wrapped function (except for the final callback argument). Errors thrown will be passed to the callback.

__Example__

```js
async.waterfall([
  async.apply(fs.readFile, filename, "utf8"),
  async.asyncify(JSON.parse),
  function (data, next) {
    // data is the result of parsing the text.
    // If there was a parsing error, it would have been caught.
  }
], callback)
```

If the function passed to `asyncify` returns a Promise, that promises's resolved/rejected state will be used to call the callback, rather than simply the synchronous return value.  Example:

```js
async.waterfall([
  async.apply(fs.readFile, filename, "utf8"),
  async.asyncify(function (contents) {
    return db.model.create(contents);
  }),
  function (model, next) {
    // `model` is the instantiated model object. 
    // If there was an error, this function would be skipped.
  }
], callback)
```

This also means you can asyncify ES2016 `async` functions.

```js
var q = async.queue(async.asyncify(async function (file) {
  var intermediateStep = await processFile(file);
  return await somePromise(intermediateStep)
}));

q.push(files);
```

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

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

Logs the result of an `async` function to the `console`. Only works in Node.js or
in browsers that support `console.log` and `console.error` (such as FF and Chrome).
If multiple arguments are returned from the async function, `console.log` is
called on each argument in order.

__Arguments__

* `function` - The function you want to eventually apply all arguments to.
* `arguments...` - Any number of arguments to apply to the function.

__Example__

```js
var hello = function(name, callback){
    setTimeout(function(){
        callback(null, 'hello ' + name);
    }, 1000);
};
```
```js
node> async.log(hello, 'world');
'hello world'
```

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

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

Logs the result of an `async` function to the `console` using `console.dir` to
display the properties of the resulting object. Only works in Node.js or
in browsers that support `console.dir` and `console.error` (such as FF and Chrome).
If multiple arguments are returned from the async function, `console.dir` is
called on each argument in order.

__Arguments__

* `function` - The function you want to eventually apply all arguments to.
* `arguments...` - Any number of arguments to apply to the function.

__Example__

```js
var hello = function(name, callback){
    setTimeout(function(){
        callback(null, {hello: name});
    }, 1000);
};
```
```js
node> async.dir(hello, 'world');
{hello: 'world'}
```

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

<a name="noConflict" />
### noConflict()

Changes the value of `async` back to its original value, returning a reference to the
`async` object.