From b5297fe5d44ae1a40f6e13204b010f98a338d446 Mon Sep 17 00:00:00 2001 From: Alex Krolick Date: Tue, 20 Oct 2015 14:19:40 -0700 Subject: [PATCH] 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 --- docs/Network.md | 47 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/docs/Network.md b/docs/Network.md index 020b8d196..d0366e646 100644 --- a/docs/Network.md +++ b/docs/Network.md @@ -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); }); -``` \ No newline at end of file +```