使用回调,您总是通过一个函数“响应”。例如:
function getUsers (age, done) {
// done has two parameters: err and result
return User.find({age}, done)
}
Promises 让你根据当前状态做出响应:
function getUsers (age) {
return new Promise((resolve, reject) => {
User.find({ age }, function (err, users) {
return err ? reject(err) : resolve(users)
})
})
}
这使“回调金字塔”变平。代替
getUsers(18, function (err, users) {
if (err) {
// handle error
} else {
// users available
}
})
您可以使用:
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
})
所以,要回答你的问题,首先你要为你的 http 请求使用一个承诺:
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()
})
}
然后,您希望将其合并到您的loadRates
函数中:
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
})
}
然后,在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()
})
}