then(onFulfilled, onRejected) {
if (typeof onFulfilled !== 'function') {
onFulfilled = function (value) {
return value
}
}
if (typeof onRejected !== 'function') {
onRejected = function (reason) {
return reason
}
}
const promise = new Promise((resolve, reject) => {
if (this.state === 'fulfilled') {
try {
const result = onFulfilled(this.value)
check(promise, result, resolve, reject)
} catch (e) {
reject(e)
}
}
if (this.state === 'rejected') {
try {
const result = onRejected(this.reason)
check(promise, result, resolve, reject)
} catch (e) {
reject(e)
}
}
if (this.state === 'pending') {
this.onFulfilledCallback.push((value) => {
try {
const result = onFulfilled(value)
check(promise, result, resolve, reject)
} catch (e) {
reject(e)
}
})
this.onRejectedCallback.push((reason) => {
try {
const result = onRejected(reason)
check(promise, result, resolve, reject)
} catch (e) {
reject(e)
}
})
}
})
return promise
}
function check(promise1, promise2, resolve, reject) {
if (promise1 === promise2) {
reject('Chaining cycle detected for Promise')
} else {
if (promise2 instanceof Promise) {
promise2.then(resolve, reject)
} else {
resolve(promise2)
}
}
}
}
Wait for all promises to be resolved, or for any to be rejected. If the returned promise resolves, it is resolved with an aggregating array of the values from the resolved promises in the same order as defined in the iterable of multiple promises.
Wait until any of the promises is resolved or rejected. If the returned promise resolves, it is resolved with the value of the first promise in the iterable that resolved. If it rejects, it is rejected with the reason from the first promise that was rejected.
Returns a new Promise object that is resolved with the given value.