我已经阅读了所有关于JS promises的文章,但我仍然无法理解它们。我正在尝试使用promises来管理多个XMLHTTPRequests。例如:当xhr请求1&2完成时,调用此函数。
示例代码:
function initSession(){
loadRates(0);
loadRates(10);
buildTable();
// Get all rates from API, save to localStorage, then build the table.
}
function loadRates(days) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
// save response to localStorage, using a custom variable
localStorage.setItem("rates" + days, xhr.responseText);
};
xhr.open('GET', url);
xhr.send();
}
function buildTable() {
// get data from localStorage
// write to HTML table
}在这种情况下,我如何将每个函数调用包装在Promise对象中,以便我可以控制它们何时被调用?
发布于 2015-07-17 05:03:12
对于回调,你总是通过一个函数来“响应”。例如:
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请求使用promise:
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()
})
}发布于 2015-07-18 04:35:45
此外,请注意,有一个方便的函数可以发出AJAX-request并获取promise - window.fetch。Chrome和火狐已经支持它了,对于其他浏览器,它可以是polyfilled。
然后你就可以轻松地解决你的问题了
function loadRates(days) {
return window.fetch(url).then(function(response) {
return response.json(); // needed to parse raw response data
}).then(function(response) {
localStorage.setItem("rates" + days, response);
return response; // this return is mandatory, otherwise further `then` calls will get undefined as argument
});
}
Promise.all([
loadRates(0),
loadRates(1)
]).then(function(rates) {
return buildTable(rates)
})https://stackoverflow.com/questions/31463538
复制相似问题