Created
December 17, 2019 17:45
-
-
Save stefanfrede/c0c67dac8d736136b060a2d1162903fb to your computer and use it in GitHub Desktop.
Chained APIs with Asynchronous Functions
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
// Given | |
class Solar { | |
getBaseMap(callback) { | |
setTimeout(function() { | |
callback(); | |
console.log('Getting Base Map'); | |
}, 600); | |
} | |
drawRoofOutline(callback) { | |
setTimeout(function() { | |
callback(); | |
console.log('User Outlining Roof'); | |
}, 1000); | |
} | |
generate3Dmodel(callback) { | |
setTimeout(function() { | |
callback(); | |
console.log('Generating 3D model'); | |
}, 750); | |
} | |
calculateIrradiance(callback) { | |
setTimeout(function() { | |
callback(); | |
console.log('Calculating Irradiance'); | |
}, 2000); | |
} | |
placeSolarPanels(callback) { | |
setTimeout(function() { | |
callback(); | |
console.log('Placing Solar Panels'); | |
}, 500); | |
} | |
simulatePowerSavings(callback) { | |
setTimeout(function() { | |
callback(); | |
console.log('Simulating Power Savings'); | |
}, 3000); | |
} | |
} | |
// http://blog.minimum.se/2017/07/18/fluent-chained-api-asynchronous-functions-async-methods-Javascript.html | |
// https://stackoverflow.com/questions/49766184/how-to-chain-async-methods | |
const slr = new Solar(); | |
const resolve = (prevAction, fn, cb) => { | |
return prevAction | |
.then(() => new Promise(resolve => fn(resolve))) | |
.then(res => cb ? cb(res) : res); | |
}; | |
const Api = (prevAction = Promise.resolve()) => ({ | |
getBaseMap: (cb) => Api( | |
resolve(prevAction, slr.getBaseMap, cb) | |
), | |
drawRoofOutline: (cb) => Api( | |
resolve(prevAction, slr.drawRoofOutline, cb) | |
), | |
generate3Dmodel: (cb) => Api( | |
resolve(prevAction, slr.generate3Dmodel, cb) | |
), | |
calculateIrradiance: (cb) => Api( | |
resolve(prevAction, slr.calculateIrradiance, cb) | |
), | |
placeSolarPanels: (cb) => Api( | |
resolve(prevAction, slr.placeSolarPanels, cb) | |
), | |
simulatePowerSavings: (cb) => Api( | |
resolve(prevAction, slr.simulatePowerSavings, cb) | |
), | |
}); | |
solar = Api(); | |
solar | |
.getBaseMap() | |
.drawRoofOutline() | |
.generate3Dmodel() | |
.calculateIrradiance() | |
.placeSolarPanels() | |
.simulatePowerSavings(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment