全部代碼
function Promise_c(func) {
this._then = []
this._catch = function (err) {
throw err
}
func(this.resolve.bind(this), this.reject.bind(this))
return this
}
Promise_c.prototype.resolve = function (res) {
if (this._then.length) {
var func = this._then.shift()
var next = func(res)
if (next instanceof Promise_c) {
next._then = [].concat(next._then, this._then)
} else {
this.resolve(next)
}
}
}
Promise_c.prototype.reject = function (err) {
this._catch && this._catch(err)
}
Promise_c.prototype.then = function (func) {
this._then.push(func)
return this
}
Promise_c.prototype.catch = function (func) {
this._catch = func
return this
}
if (next instanceof Promise_c) {
next._then = [].concat(next._then, this._then)
}
這行代碼是核心书劝, 如果上一個 then 返回的是 Primise 實例
就講 當前Promise下所有未執(zhí)行的 then 函數(shù) 全部移交給 next 的 Promise 實例
這時當前 Promise的任務已經完成
new Promise_c(function (resolve, reject) {
setTimeout(function () {
resolve('hello :1')
}, 2000)
}).then(function (res) {
console.log(res, 1)
// hello :1 1
return new Promise_c(function (resolve, reject) {
setTimeout(function () {
resolve(res + ':' + 2)
}, 2000)
})
}).then(function (res) {
console.log(res, 2)
// hello :1:2 2
})
new Promise_c(function (resolve, reject) {
setTimeout(function () {
resolve('hello :1')
}, 2000)
}).then(function (res) {
console.log(res, 1)
// hello :1 1
return new Promise_c(function (resolve, reject) {
setTimeout(function () {
resolve(res + ':' + 2)
}, 2000)
}).then(function (res) {
console.log(res, 2)
// hello :1:2 2
})
})
也就是說這兩種調用的形式痕檬,最后被執(zhí)行的結果是相同的原献,而且如果使用第一種寫法(如果業(yè)務邏輯是如此)
最后執(zhí)行的時候回被轉化成第二種形式