JavaScript Promise 异步编程的一些代码分享

基本用法

const promise = new Promise((resolve, reject) => {
    // 如果成功
    resolve(33)

    // 如果失败
})

// 使用
promise.then(
    v => console.log(v), // 成功
    err => console.log(err) // 失败
)

错误处理

const promise = new Promise((resolve, reject) => {
    // 如果成功
    // resolve(33)

    // 如果失败
    reject(new Error("promise rejected"))
})

// 使用
promise.then(
    v => console.log(v), // 成功
    err => console.log(err) // 失败
)

模拟 Ajax 请求

// 模拟 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 发送并发请求

// 模拟 ajax 方法
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 发送请求

// 模拟 ajax 方法
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)
    // 向每个 URL 并行的发请求
    const tasks = urls.map(url => ajax(url))
    return Promise.all(tasks)
}).then(values => console.log(values))
    .catch(err => console.log(err))

通过 race 实现超时处理

// 模拟 ajax 方法
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))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Python私教

创业不易,请打赏支持我一点吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值