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)
6 Utility 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.
12 npm install --save run-async
18 Here's a simple example print the function results and three options a user can provide a function.
21 var runAsync = require('run-async');
23 var printAfter = function (func) {
24 var cb = function (err, returnValue) {
25 console.log(returnValue);
27 runAsync(func, cb)(/* arguments for func */);
31 #### Using `this.async`
33 printAfter(function () {
34 var done = this.async();
36 setTimeout(function () {
37 done(null, 'done running with callback');
42 #### Returning a promise
44 printAfter(function () {
45 return new Promise(function (resolve, reject) {
46 resolve('done running with promises');
51 #### Synchronous function
53 printAfter(function () {
54 return 'done running sync function';
60 `runAsync.cb` supports all the function types that `runAsync` does and additionally a traditional **callback as the last argument** signature:
63 var runAsync = require('run-async');
65 // IMPORTANT: The wrapped function must have a fixed number of parameters.
66 runAsync.cb(function(a, b, cb) {
68 }, function(err, result) {
73 If your version of node support Promises natively (node >= 0.12), `runAsync` will return a promise. Example: `runAsync(func)(arg1, arg2).then(cb)`
78 Copyright (c) 2014 Simon Boudrias (twitter: @vaxilart)
79 Licensed under the MIT license.