UNPKG

2.11 kBMarkdownView Raw
1Run Async
2=========
3
4[![npm](https://badge.fury.io/js/run-async.svg)](http://badge.fury.io/js/run-async) [![tests](https://travis-ci.org/SBoudrias/run-async.svg?branch=master)](http://travis-ci.org/SBoudrias/run-async) [![dependencies](https://david-dm.org/SBoudrias/run-async.svg?theme=shields.io)](https://david-dm.org/SBoudrias/run-async)
5
6Utility method to run a function either synchronously or asynchronously using a series of common patterns. This is useful for library author accepting sync or async functions as parameter. `runAsync` will always run them as an async method, and normalize the multiple signature.
7
8Installation
9=========
10
11```bash
12npm install --save run-async
13```
14
15Usage
16=========
17
18Here's a simple example print the function results and three options a user can provide a function.
19
20```js
21var runAsync = require('run-async');
22
23var printAfter = function (func) {
24 var cb = function (err, returnValue) {
25 console.log(returnValue);
26 };
27 runAsync(func, cb)(/* arguments for func */);
28};
29```
30
31#### Using `this.async`
32```js
33printAfter(function () {
34 var done = this.async();
35
36 setTimeout(function () {
37 done(null, 'done running with callback');
38 }, 10);
39});
40```
41
42#### Returning a promise
43```js
44printAfter(function () {
45 return new Promise(function (resolve, reject) {
46 resolve('done running with promises');
47 });
48});
49```
50
51#### Synchronous function
52```js
53printAfter(function () {
54 return 'done running sync function';
55});
56```
57
58### runAsync.cb
59
60`runAsync.cb` supports all the function types that `runAsync` does and additionally a traditional **callback as the last argument** signature:
61
62```js
63var runAsync = require('run-async');
64
65// IMPORTANT: The wrapped function must have a fixed number of parameters.
66runAsync.cb(function(a, b, cb) {
67 cb(null, a + b);
68}, function(err, result) {
69 console.log(result)
70})(1, 2)
71```
72
73If your version of node support Promises natively (node >= 0.12), `runAsync` will return a promise. Example: `runAsync(func)(arg1, arg2).then(cb)`
74
75Licence
76========
77
78Copyright (c) 2014 Simon Boudrias (twitter: @vaxilart)
79Licensed under the MIT license.