Merge pull request #3552 from whokilledtheelectricmonk/patch-1

extend Network/Fetch API documentation
This commit is contained in:
James Ide 2015-11-02 10:02:02 -08:00
commit a456ac3ced
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
[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 ```javascript
fetch('https://mywebsite.com/endpoint.php') 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
WebSocket is a protocol providing full-duplex communication channels over a single TCP connection. WebSocket is a protocol providing full-duplex communication channels over a single TCP connection.