Progression from Callbacks
suggest changeIn the beginning there were callbacks, and callbacks were fine. http in these samples is a stand-in client whose callback receives { data }. It is not Node's http.get.
const getTemperature = (callback) => {
http.get('www.temperature.com/current', (res) => {
callback(res.data.temperature)
})
}
const getAirPollution = (callback) => {
http.get('www.pollution.com/current', (res) => {
callback(res.data.pollution)
});
}
getTemperature(function(temp) {
getAirPollution(function(pollution) {
console.log(`the temp is ${temp} and the pollution is ${pollution}.`)
// The temp is 27 and the pollution is 0.5.
})
})
But there were a few really frustrating issues with callbacks so we all started using promises.
const getTemperature = () => {
return new Promise((resolve, reject) => {
http.get('www.temperature.com/current', (res) => {
resolve(res.data.temperature)
})
})
}
const getAirPollution = () => {
return new Promise((resolve, reject) => {
http.get('www.pollution.com/current', (res) => {
resolve(res.data.pollution)
})
})
}
getTemperature()
.then(temp => console.log(`the temp is ${temp}`))
.then(() => getAirPollution())
.then(pollution => console.log(`and the pollution is ${pollution}`))
// the temp is 32
// and the pollution is 0.5
This was a bit better. async/await still uses promises. Top-level await needs an ES module; inside CommonJS, put it in an async function:
async function report() {
const temp = await getTemperature()
const pollution = await getAirPollution()
console.log(`the temp is ${temp} and the pollution is ${pollution}.`)
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents