With callbacks, you always "respond" via one function. For example:
function getUsers (age, done) {
// done has two parameters: err and result
return User.find({age}, done)
}
Promises lets you respond according to the current state:
function getUsers (age) {
return new Promise((resolve, reject) => {
User.find({ age }, function (err, users) {
return err ? reject(err) : resolve(users)
})
})
}
This flattens the "callback pyramid." Instead of
getUsers(18, function (err, users) {
if (err) {
// handle error
} else {
// users available
}
})
You can use:
getUsers(18).then((users) => {
// `getPetsFromUserIds` returns a promise
return getPetsFromUserIds(users.map(user => user._id))
}).then((pets) => {
// pets here
}).catch((err) => {
console.log(err) // handle error
})
So, to answer your question, first you'd want to use a promise for your http requests:
function GET (url) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
return resolve(xhr.response)
} else {
return reject({ status: this.status, text: xhr.statusText })
}
}
xhr.onerror = reject
xhr.send()
})
}
Then, you'd want to incorporate this into your loadRates
function:
function loadRates (days) {
var URL = URL_GENERATOR(days)
return GET(URL).catch((err) => {
// handle our error first
console.log(err)
// decide how you want to handle a lack of data
return null
}).then((res) => {
localStorage.setItem('rates' + days, res)
return res
})
}
Then, in initSession
:
function initSession () {
Promise.all([ loadRates(0), loadRates(10) ]).then((results) => {
// perhaps you don't want to store in local storage,
// since you'll have access to the results right here
let [ zero, ten ] = results
return buildTable()
})
}