-
-
Notifications
You must be signed in to change notification settings - Fork 231
/
async.ts
115 lines (113 loc) · 3.04 KB
/
async.ts
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import { toThenable, toPromise, toValue } from '../../../src/util/async'
import { expect, use } from 'chai'
import * as chaiAsPromised from 'chai-as-promised'
use(chaiAsPromised)
describe('utils/async', () => {
describe('#toPromise()', function () {
it('should return a promise', async () => {
function * foo () {
return 'foo'
}
const result = await toPromise(foo())
expect(result).to.equal('foo')
})
})
describe('#toThenable()', function () {
it('should support iterable with single return statement', async () => {
function * foo () {
return 'foo'
}
const result = await toThenable(foo())
expect(result).to.equal('foo')
})
it('should support promise', async () => {
function foo () {
return Promise.resolve('foo')
}
const result = await toThenable(foo())
expect(result).to.equal('foo')
})
it('should resolve dependency', async () => {
function * foo () {
return yield bar()
}
function * bar () {
return 'bar'
}
const result = await toThenable(foo())
expect(result).to.equal('bar')
})
it('should support promise dependency', async () => {
function * foo () {
return yield Promise.resolve('foo')
}
const result = await toThenable(foo())
expect(result).to.equal('foo')
})
it('should reject Promise if dependency throws syncly', done => {
function * foo () {
return yield bar()
}
function * bar (): IterableIterator<any> {
throw new Error('bar')
}
toThenable(foo()).catch(err => {
expect(err.message).to.equal('bar')
done()
return 0 as any
})
})
it('should resume promise after catch', async () => {
function * foo () {
let ret = ''
try {
yield bar()
} catch (e) {
ret += 'bar'
}
ret += 'foo'
return ret
}
function * bar (): IterableIterator<any> {
throw new Error('bar')
}
const ret = await toThenable(foo())
expect(ret).to.equal('barfoo')
})
})
describe('#toValue()', function () {
it('should throw Error if dependency throws syncly', () => {
function * foo () {
return yield bar()
}
function * bar (): IterableIterator<any> {
throw new Error('bar')
}
expect(() => toValue(foo())).to.throw('bar')
})
it('should resume yield after catch', () => {
function * foo () {
try {
yield bar()
} catch (e) {}
return yield 'foo'
}
function * bar (): IterableIterator<any> {
throw new Error('bar')
}
expect(toValue(foo())).to.equal('foo')
})
it('should resume return after catch', () => {
function * foo () {
try {
yield bar()
} catch (e) {}
return 'foo'
}
function * bar (): IterableIterator<any> {
throw new Error('bar')
}
expect(toValue(foo())).to.equal('foo')
})
})
})