JavaScript: Promise async await
- 使用Promise封装ajax
function ajax (url) { return new Promise((resolve, reject) => { let xhr = new XMLHttpRequest() xhr.onreadystatechange = function () { if (this.readyState === 4) { if (this.status === 200) { console.log('resolve') resolve(this.responseText) } else { console.log('error',) reject(new Error('reject error')) } } } xhr.open('get', url) xhr.send() }) }
<script> function send () { ajax('http://localhost:555/vanity') .then(data => { console.log(data); return ajax('http://localhost:555/vanity') }, err => console.log(err)) .then(data => { console.log(data); return ajax('http://localhost:555/vanity') }, err => console.log(err)) .then(data => { console.log(data); return ajax('http://localhost:555/vanity') }, err => console.log(err)) .then(data => console.log(data), err => console.log(err)) } </script>
- Promise实现
class MyPromise { status = 'pending' // 初始状态 value = undefined reason = undefined onfulfilled = undefined onrejected = undefined constructor(executor) { console.log('constructor') executor(this.resolve, this.reject) } resolve = value => { console.log('resolve') if(this.status !== 'pending') return this.status = 'fulfilled' this.value = value this.onfulfilled && this.onfulfilled(this.value) } reject = reason => { console.log('reject') if(this.status !== 'pending') return this.status = 'rejected' this.reason = reason this.onrejected && this.onrejected(this.reason) } then(onfulfilled, onrejected) { console.log('call then') if(this.status === 'fulfilled') { console.log('then fulfilled') onfulfilled(this.value) } else if(this.status === 'rejected') { console.log('then reject') onrejected(this.reason) } else { // 异步回调必定到此处 console.log('then pending') this.onfulfilled = onfulfilled // 为当前Promise对象绑定then的成功回调 this.onrejected = onrejected // 为当前Promise对象绑定then的失败回调 } } }
fs.readFile
import fs from 'fs' let pp = new MyPromise((resolve, reject) => { fs.readFile('./a.txt', 'utf8', (err, data) => { if(err) { // readFile异步回调进入EventLoop, 必定后于then执行 reject(err) } else { resolve(data) } }) }) // 绑定成功和失败的执行函数 pp.then(data => console.log(data), err => console.log(err))
new Date().getTime() 模拟
let promise = new MyPromise((resolve, reject) => { setTimeout(() => { const timestamp = new Date().getTime() if(timestamp % 2) { resolve(`odd ${timestamp}`) } else { reject(`even ${timestamp}`) } },1000) }) promise.then(value => { console.log('success', value) }, err => { console.log('fail', err) })
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律