UNPKG

582 BJavaScriptView Raw
1
2function sync (fn) {
3 var res
4 var tries = 3
5
6 while (--tries) {
7 try {
8 res = fn()
9 } catch (err) {
10 if (err.code === 'EEXIST') continue
11
12 throw err
13 }
14
15 return res
16 }
17
18 throw new Error('Failed to find unique name')
19}
20
21function async (fn, cb) {
22 var tries = 3
23
24 ;(function next () {
25 fn(function (err, res) {
26 if (!err) return cb(null, res)
27 if (err.code !== 'EEXIST') return cb(err)
28 if (--tries === 0) return cb(new Error('Failed to find unique name'))
29
30 next()
31 })
32 }())
33}
34
35exports.sync = sync
36exports.async = async