基本用法
const promise = new Promise((resolve, reject) => {
resolve(33)
})
promise.then(
v => console.log(v),
err => console.log(err)
)
错误处理
const promise = new Promise((resolve, reject) => {
reject(new Error("promise rejected"))
})
promise.then(
v => console.log(v),
err => console.log(err)
)
模拟 Ajax 请求
const ajax = url => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open("GET", url)
xhr.responseType = "json"
xhr.onload = () => {
console.log("xxx", this)
if (this.status === 200) {
resolve(this.response)
} else {
reject(new Error(this.statusText))
}
}
xhr.send()
})
}
ajax("https://reqres.in/api/users?page=2").then(
res => console.log(res),
error => console.log(error)
)
通过 all 发送并发请求
function ajax(url) {
return new Promise(function (resolve, reject) {
const xhr = new XMLHttpRequest()
xhr.open("GET", url)
xhr.responseType = "json"
xhr.onload = function () {
console.log("xxx", this)
if (this.status === 200) {
resolve(this.response)
} else {
reject(new Error(this.statusText))
}
}
xhr.send()
})
}
const req = Promise.all([
ajax("/users.json"),
ajax("/users.json"),
ajax("/users.json"),
])
req.then(vals => console.log(vals))
.catch(err => console.log("失败了:", err))
获取所有 URL 然后并发向每个 URL 发送请求
function ajax(url) {
return new Promise(function (resolve, reject) {
const xhr = new XMLHttpRequest()
xhr.open("GET", url)
xhr.responseType = "json"
xhr.onload = function () {
if (this.status === 200) {
resolve(this.response)
} else {
reject(new Error(this.statusText))
}
}
xhr.send()
})
}
ajax("/urls.json").then(v => {
const urls = Object.values(v)
const tasks = urls.map(url => ajax(url))
return Promise.all(tasks)
}).then(values => console.log(values))
.catch(err => console.log(err))
通过 race 实现超时处理
function ajax(url) {
return new Promise(function (resolve, reject) {
const xhr = new XMLHttpRequest()
xhr.open("GET", url)
xhr.responseType = "json"
xhr.onload = function () {
if (this.status === 200) {
resolve(this.response)
} else {
reject(new Error(this.statusText))
}
}
xhr.send()
})
}
const req = ajax("/users.json")
const timeout = new Promise((resolve, reject) => {
setTimeout(() => reject(new Error("timeout")), 500)
})
Promise.race([req, timeout])
.then(v => console.log(v))
.catch(err => console.log("失败了", err))