-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
38 lines (32 loc) · 916 Bytes
/
index.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
'use strict'
function isGen(fn) {
if (!(typeof fn == 'function')) return false
return fn.constructor.name == 'GeneratorFunction'
}
module.exports = function generatorToPromise(generatorFunction) {
if (!isGen(generatorFunction))
throw new Error('The given function must be a generator function')
return function invoker() {
const deferred = Promise.defer()
const generator = generatorFunction.call(this, arguments)
;(function next(error, value) {
let genState = null
try {
if (error)
genState = generator.throw(error)
else
genState = generator.next(value)
} catch (e) {
genState = { value: Promise.reject(e), done: true }
}
if (genState.done) {
deferred.resolve(genState.value)
} else {
Promise.resolve(genState.value)
.then(promiseResult => next(null, promiseResult))
.catch(error => next(error))
}
})()
return deferred.promise
}
}