mirror of
https://github.com/status-im/react-native.git
synced 2025-02-09 16:14:47 +00:00
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:
parent
e6a39a1d18
commit
4b722d6d2a
@ -41,29 +41,34 @@ fetch('https://mywebsite.com/endpoint/', {
|
|||||||
|
|
||||||
1. Using `then` and `catch` in synchronous code:
|
1. Using `then` and `catch` in synchronous code:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
fetch('https://mywebsite.com/endpoint.php')
|
fetch('https://mywebsite.com/endpoint.php')
|
||||||
.then((response) => response.text())
|
.then((response) => response.text())
|
||||||
.then((responseText) => {
|
.then((responseText) => {
|
||||||
console.log(responseText);
|
console.log(responseText);
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
console.warn(error);
|
console.warn(error);
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
2. Called within an asynchronous function using ES7 `async`/`await` syntax:
|
2. Called within an asynchronous function using ES7 `async`/`await` syntax:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
async getUsersFromApi() {
|
class MyComponent extends React.Component {
|
||||||
try {
|
...
|
||||||
let response = await fetch('https://mywebsite.com/endpoint/');
|
async getUsersFromApi() {
|
||||||
return response.users;
|
try {
|
||||||
} catch(error) {
|
let response = await fetch('https://mywebsite.com/endpoint/');
|
||||||
throw error;
|
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
|
- Note: Errors thrown by rejected Promises need to be caught, or they will be swallowed silently
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user