Skip to content

Commit

Permalink
Add recommendation for async code
Browse files Browse the repository at this point in the history
  • Loading branch information
garethbowen committed Aug 15, 2022
1 parent 13a1422 commit ee69628
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions content/en/contribute/code/style-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,47 @@ function isPercentage(val) {
}
```

## Asynchronous code

Where possible, use the async/await pattern for asynchronous code as it's generally easy to read as the statements line up down the screen. This may not be possible for legacy browser or Node version support, where promises should be used instead. Occasionally promises are better, for example, for executing multiple async methods in parallel. Avoid callbacks at all costs.

*Right:*

```js
async function fetch() {
try {
const response = await request.get();
return response.data;
} catch(e) {
// handle error
}
}
```

*Wrong:*

```js
function fetch() {
return request.get()
.then(response => response.data)
.catch(err => /* handle error */);
}
```

*Wronger:*

```js
function fetch(callback) {
return request.get((err, response) => {
if (err) {
// handle error
return;
}
callback(null, response.data);
});
}
```

## Avoid reduce

Most uses of reduce have more readable alternatives.
Expand Down

0 comments on commit ee69628

Please sign in to comment.