-
Notifications
You must be signed in to change notification settings - Fork 0
/
async.js
41 lines (39 loc) · 1.31 KB
/
async.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*jshint -W082 */
/*globals define, self*/
(function() {
'use strict';
// async function takes a generator, and optional "this"
function async(func, self) {
if (typeof func !== 'function') {
throw new TypeError('Expected a Function or GeneratorFunction.');
}
// returns returns a function asyncFunction that returns promise
// It is called with zero or more arguments...
return function asyncFunction() {
function step(resultObj) {
const p = Promise.resolve(resultObj.value); // Normalize thenables
return (resultObj.done) ? p : p
.then(result => step(gen.next(result)))
.catch(error => step(gen.throw(error)));
}
const args = Array.from(arguments);
const gen = (function*() {
return (func.constructor.name === 'GeneratorFunction') ?
yield * func.apply(self, args) : func.apply(self, args);
}());
try {
return step(gen.next());
} catch (err) {
return Promise.reject(err);
}
};
}
async.task = (func, self) => async(func, self)();
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = async;
} else if (typeof define === 'function' && define.amd) {
define([], () => async);
} else {
(self || window).async = async;
}
}());