1 | import chai = require('chai');
|
2 | import Promise = require('bluebird');
|
3 | import async = require('../src/async/index');
|
4 | import await = require('../src/await/index');
|
5 | var expect = chai.expect;
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | describe('The await(...) function', () => {
|
12 |
|
13 | it('throws if not called within a suspendable function', () => {
|
14 | expect(() => await(111)).to.throw(Error);
|
15 | });
|
16 |
|
17 | it('suspends the suspendable function until the expression produces a result', done => {
|
18 | var x = 5;
|
19 | var foo = async (() => {
|
20 | await (Promise.delay(40));
|
21 | x = 7;
|
22 | await (Promise.delay(40));
|
23 | x = 9;
|
24 | });
|
25 | foo();
|
26 | Promise.delay(20)
|
27 | .then(() => expect(x).to.equal(5))
|
28 | .then(() => Promise.delay(40))
|
29 | .then(() => expect(x).to.equal(7))
|
30 | .then(() => Promise.delay(40))
|
31 | .then(() => expect(x).to.equal(9))
|
32 | .then(() => done())
|
33 | .catch(done);
|
34 | expect(x).to.equal(5);
|
35 | });
|
36 |
|
37 | it('resumes the suspendable function with the value of the awaited expression', done => {
|
38 | var foo = async (() => await (Promise.delay(20).then(() => 'blah')));
|
39 | foo()
|
40 | .then(result => expect(result).to.equal('blah'))
|
41 | .then(() => done())
|
42 | .catch(done);
|
43 | });
|
44 |
|
45 | it('throws into the suspendable function the error produced by the awaited expression', done => {
|
46 | var foo = async (() => await (Promise.delay(20).then(() => { throw new Error('blah'); })));
|
47 | foo()
|
48 | .then(() => done(new Error('foo() should have rejected')))
|
49 | .catch(err => { expect(err.message).to.equal('blah'); done(); });
|
50 | });
|
51 |
|
52 | it('resumes the suspendable function with all the results of a concurrent expression', done => {
|
53 | var foo = async (() => await (Promise.delay(40).then(() => 'foo')));
|
54 | var bar = async (() => await (Promise.delay(20).then(() => 'bar')));
|
55 | var all = async (() => await([foo(), bar()]));
|
56 | all()
|
57 | .then(result => expect(result).to.deep.equal(['foo', 'bar']))
|
58 | .then(() => done())
|
59 | .catch(done);
|
60 | });
|
61 |
|
62 | it('throws into the suspendable function the first error in a concurrent expression', done => {
|
63 | var foo = async (() => await (Promise.delay(40).then(() => { throw new Error('foo'); })));
|
64 | var bar = async (() => await (Promise.delay(20).then(() => { throw new Error('bar'); })));
|
65 | var all = async (() => await([foo(), bar()]));
|
66 | all()
|
67 | .then(() => done(new Error('all() should have rejected')))
|
68 | .catch(err => { expect(err.message).to.equal('bar'); done(); });
|
69 | });
|
70 | });
|
71 |
|
72 |
|