promise.js
//构造函数的参数是一个异步任务
function Promise1(task) {
let that = this
that.status = 'pending' //默认状态是pending
that.value = undefined
//存放着所以成功的回调函数
that.onResolvedCallbacks = []
//存放着所以成功的失败函数
that.onRejectedCallbacks = []
// 调用此方法可以吧当前的promise变成成功态
function resolve(value) {
that.status = 'fulfilled'
that.value = value
that.onResolvedCallbacks.forEach((item) => item(value))
}
// 调用此方法可以吧当前的promise变成失败态
function reject(value) {
that.status = 'rejected'
that.value = value
that.onRejectedCallbacks.forEach((item) => item(value))
}
//立刻执行
try {
task(resolve, reject)
} catch (error) {
reject(error)
}
}
//onFullfiled 成功回调 onRejeect 失败回调
Promise1.prototype.then = function(onFullfiled, onReject) {
let that = this
if (that.status == 'fulfilled') {
onFullfiled(that.value)
}
if (that.status == 'rejected') {
onReject(that.value)
}
if (that.status == 'pending') {
that.onResolvedCallbacks.push(onFullfiled)
that.onRejectedCallbacks.push(onReject)
}
}
//使用require来引用
module.exports = Promise1
调用
var Promise1 = require('./Promise原理')
let p = new Promise1(function(resolve, reject) {
setTimeout(function() {
let num = Math.random()
if (num > 0.5) {
resolve('成功')
} else {
reject('失败')
}
}, 2000)
})