-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
53 lines (43 loc) · 1.13 KB
/
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*!
* make-callback <https://github.com/tunnckoCore/make-callback>
*
* Copyright (c) 2015 Charlike Mike Reagent <@tunnckoCore> (http://www.tunnckocore.tk)
* Released under the MIT license.
*/
'use strict'
var isGenerator = require('is-es6-generator')
var isSyncFn = require('is-sync-function')
var handleArguments = require('handle-arguments')
module.exports = function makeCallback (fn) {
if (!isSyncFn(fn)) {
throw new TypeError('make-callback expect sync function')
}
return function () {
var argz = handleArguments(arguments)
if (!argz.callback) {
throw new TypeError('async `fn` expect a callback')
}
var res = false
try {
res = fn.apply(fn, argz.args)
} catch (err) {
return argz.callback(err)
}
function handle (result) {
if (result.done) {
return result.value
}
try {
return handle(res.next(result.value))
} catch (err) {
return argz.callback(err)
}
}
if (!isGenerator(res)) {
argz.callback(null, res)
return null
}
res = handle(res.next())
return res ? argz.callback(null, res) : null
}
}