JavaScript 基于生成器的异步编程方案相关代码分享

基本的生成器

js 复制代码
// 定义生成器函数
function * foo(){
    console.log("start")
}

// 创建生成器
const generator = foo()

// 调用生成器
generator.next()

生成器的返回值

js 复制代码
// 定义生成器函数
function* foo() {
    console.log("start")

    // 通过 yield 返回内容
    yield "mara"
}

// 创建生成器
const generator = foo()

// 调用生成器
const result = generator.next()
console.log("result=", result)

生成器的参数

js 复制代码
// 定义生成器函数
function* foo() {
    console.log("start")

    // 通过 yield 返回内容
    const arg = yield "mara"
    console.log("arg = ", arg)
}

// 创建生成器
const generator = foo()

// 调用生成器
const result = generator.next()
console.log("result=", result)

// 再调用一次,才能执行到 yield 之后
generator.next("hello")

生成器结合 ajax 使用

js 复制代码
// 模拟 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()
    })
}

// 定义生成器函数
function* userRequest() {
    const users = yield ajax("/users.json")
    console.log(users)
}

// 创建生成器
const generator = userRequest()

// 调用生成器
const result = generator.next()

// 进行处理
result.value.then(data => generator.next(data))

多个 ajax 请求

js 复制代码
// 模拟 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()
    })
}

// 定义生成器函数
function* userRequest() {
    const users = yield ajax("/users.json")
    console.log(users)

    // 继续发请求
    const urls = yield ajax("/urls.json")
    console.log(urls)
}

// 创建生成器
const generator = userRequest()

// 调用生成器
let result = generator.next()

// 进行处理
result.value.then(data => {
    if (data.done) return

    result = generator.next(data)
    if (result.done) return;

    result.value.then(data=>{
        if (data.done) return
        generator.next()
    })
})

错误处理

js 复制代码
// 模拟 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()
    })
}

// 定义生成器函数
function* userRequest() {
    const users = yield ajax("/users.json")
    console.log(users)

    // 继续发请求
    const urls = yield ajax("/urls.json")
    console.log(urls)

    // 发送一个错误的请求
    try{
        const mockError = yield ajax("/urls333.json")
        console.log("mockError", mockError)
    }catch (e){
        console.log("xxx", e)
    }
}

// 创建生成器
const generator = userRequest()

// 调度方法
function handleResult(result) {
    if (result.done) return
    result.value.then(data => {
        handleResult(generator.next(data))
    }).catch(err => generator.throw(err))
}

// 执行调度
handleResult(generator.next())

封装通用的执行器方法

js 复制代码
// 模拟 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()
    })
}

// 定义生成器函数
function* userRequest() {
    const users = yield ajax("/users.json")
    console.log(users)

    // 继续发请求
    const urls = yield ajax("/urls.json")
    console.log(urls)

    // 发送一个错误的请求
    try{
        const mockError = yield ajax("/urls333.json")
        console.log("mockError", mockError)
    }catch (e){
        console.log("xxx", e)
    }
}

// 通用的执行器
function co(generator){
    // 创建生成器
    const g = generator()

    // 调度方法
    function handleResult(result) {
        if (result.done) return
        result.value.then(data => {
            handleResult(g.next(data))
        }).catch(err => g.throw(err))
    }

    // 执行调度
    handleResult(g.next())
}

// 调用通用的执行器
co(userRequest)

使用 async 和 await 语法糖

js 复制代码
// 模拟 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()
    })
}

// 异步方法
async function userRequest() {
    const users = await ajax("/users.json")
    console.log(users)

    // 继续发请求
    const urls = await ajax("/urls.json")
    console.log(urls)

    // 发送一个错误的请求
    try {
        const mockError = await ajax("/urls333.json")
        console.log("mockError", mockError)
    } catch (e) {
        console.log("xxx", e)
    }
}


userRequest().then(resp => console.log(resp))
    .catch(error => console.log(error))
相关推荐
千里马学框架5 天前
一起学 Android 14:ShellTransition 屏幕旋转过程深度剖析
android·智能手机·性能优化·framework·性能·屏幕旋转·rotation
美狐美颜SDK开放平台5 天前
开发直播APP时如何接入视频美颜SDK?开发流程与注意事项
android·人工智能·计算机视觉·音视频·直播美颜sdk
三十而立洋5 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
AFinalStone5 天前
Android7 SystemUI源码解析(七)Keyguard锁屏模块深度解析
android·systemui
卡布鲁5 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
致远ccc5 天前
Google Play 上架前如何测试 App?多国家 Android 环境测试
android·app测试·googleplay·多国家应用测试
李少兄5 天前
JavaScript 隐式全局变量解析
javascript
ttyyttemo5 天前
Kotlin 协程中的 Job 结构化并发与取消
android
sun0077005 天前
tbox 4g/5g切换,导致wan ip 改变,导致车机旧网络不可用。需要重启车机才行
android
沙蒿同学5 天前
我用 Go 搭了一条 AI Agent 流水线:从 1 张商品图到一整套淘宝详情页
前端·javascript·后端