原生JS実現Promise
21271 ワード
1週間に少なくとも1つの計画を完成させるために、まだ説明を書いていないので、ソースコードを置いておきます.理解しやすいように、コードを相対的に精錬するように調整しました.最近アルゴリズムとPythonの勉強に忙しいので、暇な時間に急いで説明を書きます.私があなたを助けることができることを望んで、感謝します.
ソースコード
テスト
ソースコード
function MyPromise(executor) {
var self = this
self.status = 'pending'
self.onResolvedCallback = []
self.onRejectedCallback = []
function resolve(value) {
setTimeout(function () { //
if (self.status === 'pending') {
self.status = 'resolved'
self.data = value
for (var i = 0; i < self.onResolvedCallback.length; i++) {
self.onResolvedCallback[i](value)
}
}
})
}
function reject(reason) {
setTimeout(function () { //
if (self.status === 'pending') {
self.status = 'rejected'
self.data = reason
for (var i = 0; i < self.onRejectedCallback.length; i++) {
self.onRejectedCallback[i](reason)
}
}
})
}
try {
executor(resolve, reject)
} catch (reason) {
reject(reason)
}
}
MyPromise.prototype.then = function (onResolved, onRejected) {
var self = this
var promise2
onResolved = typeof onResolved === 'function' ? onResolved : function (v) {
return v
}
onRejected = typeof onRejected === 'function' ? onRejected : function (r) {
throw r
}
if (self.status === 'resolved') {
return promise2 = new MyPromise(function (resolve, reject) {
setTimeout(function () { // onResolved
try {
var x = onResolved(self.data)
resolve(x)
} catch (reason) {
reject(reason)
}
})
})
}
if (self.status === 'rejected') {
return promise2 = new MyPromise(function (resolve, reject) {
setTimeout(function () { // onRejected
try {
var x = onRejected(self.data)
resolve(x)
} catch (reason) {
reject(reason)
}
})
})
}
if (self.status === 'pending') {
// , resolve reject , resolve reject ,
return promise2 = new MyPromise(function (resolve, reject) {
self.onResolvedCallback.push(function (value) {
try {
var x = onResolved(value)
resolve(x)
} catch (r) {
reject(r)
}
})
self.onRejectedCallback.push(function (reason) {
try {
var x = onRejected(reason)
resolve(x)
} catch (r) {
reject(r)
}
})
})
}
}
MyPromise.prototype.catch = function (onRejected) {
return this.then(null, onRejected)
}
テスト
let myPromise1 = new MyPromise((resolve,reject)=>{
setTimeout(()=>{ resolve('==resolve==')},100)}).then((v)=>{
console.log(' ');
console.log(v);},(r)=>{
console.log(' ');
console.log(r);})
let myPromise2 = new MyPromise((resolve,reject)=>{
setTimeout(()=>{ reject('==resolve==')},100)}).catch((r)=>{console.log(r)})