Unsync
Unsync is a JavaScript library that simplifies asynchronous promises by using generators.
Requirements
To use Unsync, you need a JavaScript engine that supports both promises and generators:
- Node.js v4.0 or above
- Google Chrome 39 or above
- Firefox 31 or above
- Opera 26 or above
- Android 5.1 or above
- Microsoft Edge 13 or above
If you need backwards compatability, you can use babel.js + core-js.
API
unsync(generator, [thisArg, ...bindArgs])
Creates a new unsynced function based on the generator function generator
.
thisArg
and bindArgs
behave as if passed to Function.prototype.bind
.
Basics
You create an unsynced function by calling unsync
:
var myFunc = ;
The unsynced function is called like a normal function, and returns a promise, which is fulfilled when the function returns.
;
Calling asynchronous functions
You can call any asynchronous function that returns a promise using the yield
operator:
;
If the promise resolves to a value, this value will be returned by the yield
expression:
;
You can call multiple asynchronous functions in parallel by using the yield
operator on an array:
;
Returning values and catching errors
If the unsynced function has a return value, the promise will resolve to this value:
var myFunc = ; ;
If an uncaught error occurs in the unsynced function, or any of the called functions, then the promise is rejected.
var myFunc = ; ;
Using a custom Promise implementation
If you want to use a custom Promise implementation, such as Q or Bluebird, you can simply change the unsync.Promise
property:
// QunsyncPromise = QPromise; // BluebirdunsyncPromise = BluebirdPromise;
unsync.defer()
The defer
method is implemented for compatability with asynchronous functions that do not return promises.
When called, the defer
method returns an object with the following properties:
promise
: A deferred promise.resolve([value])
: A function that resolves the promise, with the valuevalue
.reject([reason])
: A function that rejects the promise, with the reasonreason
.callback(err, [value])
: A Node-style callback, that resolves or reject the promise based onerr
.
Example
var waitAndPrint = ; ;