Add context to async example function in Network docs

Reviewed By: svcscm

Differential Revision: D2933584

fb-gh-sync-id: 24436b185791e3fa8047be521894545c08a90ee0
shipit-source-id: 24436b185791e3fa8047be521894545c08a90ee0
This commit is contained in:
Alex Krolick 2016-02-12 13:38:32 -08:00 committed by facebook-github-bot-4
parent e6a39a1d18
commit 4b722d6d2a
1 changed files with 26 additions and 21 deletions

View File

@ -41,29 +41,34 @@ fetch('https://mywebsite.com/endpoint/', {
1. Using `then` and `catch` in synchronous code:
```js
fetch('https://mywebsite.com/endpoint.php')
.then((response) => response.text())
.then((responseText) => {
console.log(responseText);
})
.catch((error) => {
console.warn(error);
});
```
```js
fetch('https://mywebsite.com/endpoint.php')
.then((response) => response.text())
.then((responseText) => {
console.log(responseText);
})
.catch((error) => {
console.warn(error);
});
```
2. Called within an asynchronous function using ES7 `async`/`await` syntax:
```js
async getUsersFromApi() {
try {
let response = await fetch('https://mywebsite.com/endpoint/');
return response.users;
} catch(error) {
throw error;
```js
class MyComponent extends React.Component {
...
async getUsersFromApi() {
try {
let response = await fetch('https://mywebsite.com/endpoint/');
let responseJson = await response.json();
return responseJson.users;
} catch(error) {
// Handle error
console.error(error);
}
}
...
}
}
```
```
- Note: Errors thrown by rejected Promises need to be caught, or they will be swallowed silently