Last active
July 4, 2021 16:27
-
-
Save quickshiftin/227a21cd5f6b68f96e9672ef7eac8332 to your computer and use it in GitHub Desktop.
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
//-------------------------------------------------------------------- | |
// http://solutionoptimist.com/2013/12/27/javascript-promise-chains-2/ | |
//-------------------------------------------------------------------- | |
//-------------------------------------------------------------------- | |
// Pretend calls to a service | |
//-------------------------------------------------------------------- | |
function getDeparture() { | |
return new Promise((resolve) => { | |
setTimeout(function() { | |
resolve('chicago'); | |
}, 1000); | |
}); | |
} | |
function getFlight(departure) { | |
return new Promise((resolve) => { | |
setTimeout(function() { | |
resolve(departure + ' - flight 999'); | |
}, 1500); | |
}); | |
} | |
//-------------------------------------------------------------------- | |
// Anti pattern... | |
//-------------------------------------------------------------------- | |
getDeparture().then(departure => { | |
getFlight(departure).then(flight => { | |
console.log(flight); | |
}) | |
}); | |
//-------------------------------------------------------------------- | |
// Decent, but has tedious promise handlers | |
//-------------------------------------------------------------------- | |
getDeparture().then(departure => { | |
return getFlight(departure); | |
}).then(flight => { | |
console.log(flight); | |
}); | |
//-------------------------------------------------------------------- | |
// The money version | |
//-------------------------------------------------------------------- | |
function fetchDeparture() { | |
return getDeparture().then((departure) => { | |
return departure; | |
}); | |
} | |
function fetchFlight(departure) { | |
return getFlight(departure).then((flight) => { | |
console.log(flight); | |
}); | |
} | |
fetchDeparture().then(fetchFlight); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment