//resolve和reject
function Promise(fn) {
this.status = "pending"
this.value = ""
const that = this
try {
fn(resolve, reject)
} catch (e) {
reject(e)
}
function resolve(value) {
that.value = value;
that.status = "resloved"
}
function reject(value) {
that.value = value;
that.status = "rejected"
}
}
//then方法实现
Promise.prototype.then = function (onReslved, onRejected) {
if (self.status === 'resolved') {
onReslved(this.value);
}
if (self.status === 'rejected') {
onRejected(this.reason);
}
}
手写简易promise
最新推荐文章于 2024-10-30 19:10:39 发布
本文深入探讨了Promise的工作原理,并通过实际编写简易版Promise,帮助读者更好地理解和掌握异步编程的核心概念。我们将从创建一个新的Promise实例开始,实现resolve和reject方法,接着实现then和catch方法,最后通过例子展示如何使用这个简易Promise处理异步操作。
摘要由CSDN通过智能技术生成