Skip to content

Instantly share code, notes, and snippets.

@michaelwclark
Last active April 6, 2018 17:14
Show Gist options
  • Select an option

  • Save michaelwclark/7d609b8dc41bb3b640db6a5dc187b85a to your computer and use it in GitHub Desktop.

Select an option

Save michaelwclark/7d609b8dc41bb3b640db6a5dc187b85a to your computer and use it in GitHub Desktop.
Example code for destructure async errors and body for API calls.
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