欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > JavaScript 基于生成器的异步编程方案相关代码分享

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

2024/10/25 19:24:32 来源:https://blog.csdn.net/qq_37703224/article/details/142310500  浏览:    关键词:JavaScript 基于生成器的异步编程方案相关代码分享

基本的生成器

// 定义生成器函数
function * foo(){console.log("start")
}// 创建生成器
const generator = foo()// 调用生成器
generator.next()

生成器的返回值

// 定义生成器函数
function* foo() {console.log("start")// 通过 yield 返回内容yield "mara"
}// 创建生成器
const generator = foo()// 调用生成器
const result = generator.next()
console.log("result=", result)

生成器的参数

// 定义生成器函数
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 使用

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

// 模拟 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) returnresult = generator.next(data)if (result.done) return;result.value.then(data=>{if (data.done) returngenerator.next()})
})

错误处理

// 模拟 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) returnresult.value.then(data => {handleResult(generator.next(data))}).catch(err => generator.throw(err))
}// 执行调度
handleResult(generator.next())

封装通用的执行器方法

// 模拟 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) returnresult.value.then(data => {handleResult(g.next(data))}).catch(err => g.throw(err))}// 执行调度handleResult(g.next())
}// 调用通用的执行器
co(userRequest)

使用 async 和 await 语法糖

// 模拟 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))

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com