Created
February 28, 2016 03:29
-
-
Save andrewdelprete/1a825c64081f717b7551 to your computer and use it in GitHub Desktop.
Callback > Promises > Async / Await
This file contains 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 axios from 'axios' // for promise examples | |
import request from 'request' // for callback example | |
/** | |
* Services | |
*/ | |
const service = { | |
getPeople: () => axios({ url: 'http://localhost:3000/people' }), | |
getPlaces: () => axios({ url: 'http://localhost:3000/places' }) | |
} | |
/** | |
* Example #1 - Callback Hell-o | |
*/ | |
function example1() { | |
const obj = {} | |
request.get({ url: 'http://localhost:3000/people', json: true }, (err, response, body) => { | |
if (err) { | |
console.error(err) | |
} else { | |
obj.people = body | |
request.get({ url: 'http://localhost:3000/places', json: true }, (err, response, body) => { | |
if (err) { | |
console.error(err) | |
} else { | |
obj.places = body | |
console.log('Example #1', obj) | |
} | |
}) | |
} | |
}) | |
} | |
example1() | |
/** | |
* Example #2 - Promises Alone | |
*/ | |
function example2() { | |
let obj = {} | |
service.getPeople() | |
.then(response => { | |
obj.people = response.data | |
return service.getPlaces() | |
}) | |
.then(response => { | |
obj.places = response.data | |
console.log('Example #2', obj) | |
}) | |
.catch(err => { | |
console.log(err) | |
}) | |
} | |
example2() | |
/** | |
* Example #2b - Promises with Promise.all() | |
*/ | |
function example2b() { | |
Promise.all([ service.getPeople(), service.getPlaces() ]) | |
.then(values => { | |
console.log('Example #2b', values.map(v => v.data)) | |
}) | |
.catch(err => { | |
console.log(err) | |
}) | |
} | |
example2b() | |
/** | |
* Example #3 - Async / Await | |
*/ | |
async function example3() { | |
try { | |
const people = await service.getPeople() | |
const places = await service.getPlaces() | |
console.log('Example #3', { | |
people: people.data, | |
places: places.data | |
}) | |
} catch(err) { | |
console.error(err) | |
} | |
} | |
example3() | |
/** | |
* Example #3b - Async / Await with Promise.all() | |
*/ | |
async function example3b() { | |
try { | |
const values = await Promise.all([ service.getPeople(), service.getPlaces() ]) | |
console.log('Example #3b', values.map(v => v.data)) | |
} catch(err) { | |
console.error(err) | |
} | |
} | |
example3b() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👍