Skip to content

Commit 09de006

Browse files
authored
Document more async pitfalls (#1045)
* Use tabs in pitfalls code blocks * Spell out async in pitfals doc * Promote async/await in pitfalls doc * Provide example of using pify * Suggest pify for catching exceptions * Suggest promisifying callback-functions for better exception catching
1 parent 4baa170 commit 09de006

File tree

1 file changed

+31
-11
lines changed

1 file changed

+31
-11
lines changed

docs/common-pitfalls.md

+31-11
Original file line numberDiff line numberDiff line change
@@ -18,30 +18,50 @@ You may be using a service that only allows a limited number of concurrent conne
1818

1919
Use the `concurrency` flag to limit the number of processes ran. For example, if your service plan allows 5 clients, you should run AVA with `concurrency=5` or less.
2020

21-
## Async operations
21+
## Asynchronous operations
2222

23-
You may be running an async operation inside a test and wondering why it's not finishing. If your async operation uses promises, you should return the promise:
23+
You may be running an asynchronous operation inside a test and wondering why it's not finishing. If your asynchronous operation uses promises, you should return the promise:
2424

2525
```js
2626
test(t => {
27-
return fetch().then(data => {
28-
t.is(data, 'foo');
29-
});
27+
return fetch().then(data => {
28+
t.is(data, 'foo');
29+
});
3030
});
3131
```
3232

33-
If it uses callbacks, use [`test.cb`](https://github.com/avajs/ava#callback-support):
33+
Better yet, use `async` / `await`:
34+
35+
```js
36+
test(async t => {
37+
const data = await fetch();
38+
t.is(data, 'foo');
39+
});
40+
```
41+
42+
If you're using callbacks, use [`test.cb`](https://github.com/avajs/ava#callback-support):
3443

3544
```js
3645
test.cb(t => {
37-
fetch((err, data) => {
38-
t.is(data, 'bar');
39-
t.end();
40-
});
46+
fetch((err, data) => {
47+
t.is(data, 'foo');
48+
t.end();
49+
});
4150
});
4251
```
4352

44-
Alternatively, promisify the callback function using something like [pify](https://github.com/sindresorhus/pify).
53+
Alternatively, promisify the callback function using something like [`pify`](https://github.com/sindresorhus/pify):
54+
55+
```js
56+
test(async t => {
57+
const data = await pify(fetch)();
58+
t.is(data, 'foo');
59+
});
60+
```
61+
62+
### Attributing uncaught exceptions to tests
63+
64+
AVA [can't trace uncaught exceptions](https://github.com/avajs/ava/issues/214) back to the test that triggered them. Callback-taking functions may lead to uncaught exceptions that can then be hard to debug. Consider promisifying and using `async`/`await`, as in the above example. This should allow AVA to catch the exception and attribute it to the correct test.
4565

4666
---
4767

0 commit comments

Comments
 (0)