来自回调的进展
一开始有回调,回调没问题:
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.
})
})
但回调有一些非常令人沮丧的问题,所以我们都开始使用 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
这有点好。最后,我们找到了 async / await。其中仍然使用承诺。
const temp = await getTemperature()
const pollution = await getAirPollution()