Last active
April 6, 2018 17:14
-
-
Save michaelwclark/7d609b8dc41bb3b640db6a5dc187b85a to your computer and use it in GitHub Desktop.
Example code for destructure async errors and body for API calls.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import request from 'superagent-bluebird-promise' | |
| const ad = async promise => { | |
| const [err,resp] = await promise.then(x=>[{},x]).catch(x=>[x, {}]) | |
| const [{message},{body}] = [err, resp] | |
| return [message, body] | |
| } | |
| async function handlesSuccess(){ | |
| const [errorMessage, requestBody] = await ad(request.get('https://jsonplaceholder.typicode.com/posts/1').promise()) | |
| console.log({method: 'handlesSuccess', errorMessage, requestBody}) | |
| } | |
| async function handlesErrors(){ | |
| const [errorMessage, requestBody] = await ad(request.get('https://5.typicode.com/posts/1').promise()) | |
| console.log({method: 'handlesErrors', errorMessage, requestBody}) | |
| } | |
| handlesSuccess() | |
| handlesErrors() | |
| // Output: | |
| // babel-node asyncDestructure.js -b 'env' | |
| // { method: 'handlesErrors', | |
| // errorMessage: 'getaddrinfo ENOTFOUND 5.typicode.com 5.typicode.com:443', | |
| // requestBody: undefined } | |
| // { method: 'handlesSuccess', | |
| // errorMessage: undefined, | |
| // requestBody: | |
| // { userId: 1, | |
| // id: 1, | |
| // title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit', | |
| // body: 'quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut | |
| // quas totam\nnostrum rerum est autem sunt rem eveniet architecto' } } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment