Promise.all() 等待所有任务结束
function ajax (url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest()
xhr.open('GET', url)
xhr.responseType = 'json'
// readystate = 4
xhr.onload = function () {
if (this.status === 200) {
resolve(this.response)
} else {
reject(this.statusText)
}
}
xhr.send()
})
}
var promise = Promise.all([
ajax('/api/users.json'),
ajax('/api/posts.json')
])
promise.then(function(value) {
console.log(value)
}).catch(function(error) {
console.log(error)
})
ajax('/api/urls.json')
.then(value => {
const urls = Object.values(value)
const tasks = urls.map(url => ajax(url))
return Promise.all(tasks)
})
.then(values => {
console.log(values)
})
Promise.race() 只会等待第一个结束的任务
举例请求超时的处理方式
const request = ajax('/api/posts.json')
const timeout = new Promise((resolve, reject) => {
setTimeout(() => reject(new Error('timeout')), 500)
})
Promise.race([
request,
timeout
]).then(value => {
console.log(value)
})
网友评论