当前位置: 首页 > article >正文

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))

http://www.kler.cn/news/306490.html

相关文章:

  • 远程桌面内网穿透是什么?有什么作用?
  • openssl下载和创建证书
  • 如何在 Visual Studio Code 中反编译具有正确行号的 Java 类?
  • C++:opencv多边形逼近二值图轮廓--cv::approxPolyDP
  • Java集合进阶--双列集合
  • R与机器学习系列|15.可解释的机器学习算法(Interpretable Machine Learning)(下)
  • HarmonyOS开发5.0【rcp网络请求】
  • ChatGPT+2:修订初始AI安全性和超级智能假设
  • L298N电机驱动方案简介
  • JAVA:Nginx(轻量级的Web服务器、反向代理服务器)--(1)
  • JAVA学习-练习试用Java实现“串联所有单词的子串”
  • 物联网——USART协议
  • 揭开OpenAI草莓模型神秘面纱——重塑大语言模型的逻辑能力
  • np.argpartition 是 NumPy 库中的一个非常有用的函数,具体用法如下:
  • 力扣周赛:第415场周赛
  • 黑神话悟空+云技术,游戏新体验!
  • Using OpenAI API from Firebase Cloud Functions in flutter app
  • uniapp(H5)设置反向代理,设置成功后页面报错
  • 前端网络请求库:Axios
  • C++初阶学习——探索STL奥秘——vector的模拟实现
  • 20Kg载重30分钟续航多旋翼无人机技术详解
  • 微服务下功能权限与数据权限的设计与实现
  • 差分进化算法(DE算法)求解实例---旅行商问题 (TSP)
  • C语言自定义类型-联合与枚举
  • 无人机视角下落水救援检测数据集
  • Vue学习:props验证的一个小细节“Prop 名字格式”
  • 本专题大纲
  • golang学习笔记16——golang部署与运维全攻略
  • Java高级Day42-Class类
  • Linux——应用层自定义协议与序列化