extend Network/Fetch API documentation

- Mention that Fetch returns a Promise
  (makes example with .then clearer to newcomers to ES6/ES7)
- Add example of Fetch usage with second argument
  (helps clarify how e.g., a POST request to an API might be constructed)
- Add async/await example
This commit is contained in:
Alex Krolick 2015-10-20 14:19:40 -07:00 committed by Alex Krolick
parent c15ec71238
commit b5297fe5d4
1 changed files with 45 additions and 2 deletions

View File

@ -37,7 +37,34 @@ As a developer, you're probably not going to use XMLHttpRequest directly as its
## Fetch
[fetch](https://fetch.spec.whatwg.org/) is a better networking API being worked on by the standard committee and is already available in Chrome. It is available in React Native by default.
[fetch](https://fetch.spec.whatwg.org/) is a better networking API being worked on by the standards committee and is already available in Chrome. It is available in React Native by default.
#### Usage
```javascript
fetch('https://mywebsite.com/endpoint/')
```
Include a request object as the optional second argument to customize the HTTP request:
```javascript
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
})
```
#### Async
`fetch` returns a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that can be processed in two ways:
1. Using `then` and `catch` in synchronous code:
```javascript
fetch('https://mywebsite.com/endpoint.php')
@ -50,6 +77,22 @@ fetch('https://mywebsite.com/endpoint.php')
});
```
2. Called within an asynchronous function using ES7 `async`/`await` syntax:
```javascript
async getUsersFromApi() {
try {
let response = await fetch('https://mywebsite.com/endpoint/');
return response.users;
} catch(error) {
throw error;
}
}
```
- Note: Errors thrown by rejected Promises need to be caught, or they will be swallowed silently
## WebSocket
WebSocket is a protocol providing full-duplex communication channels over a single TCP connection.
@ -76,4 +119,4 @@ ws.on('close', function(e) {
// connection closed
console.log(e.code, e.reason);
});
```
```