Skip to content

Instantly share code, notes, and snippets.

@quickshiftin
Last active July 4, 2021 16:27
Show Gist options
  • Save quickshiftin/227a21cd5f6b68f96e9672ef7eac8332 to your computer and use it in GitHub Desktop.
Save quickshiftin/227a21cd5f6b68f96e9672ef7eac8332 to your computer and use it in GitHub Desktop.
//--------------------------------------------------------------------
// 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