// 测试案例 new Promise((resolve, reject) => { setTimeout(() => resolve(new Promise(
res=> res(333))), 2000) }).then(res => { console.log(res) return 222 }).then().
then(res => { console.log(res); return new Promise(res => { setTimeout(() => {
res(666) }, 1000) }).then(res => { console.log(res); return 999 }) }).then(res
=> { console.log(res); }) /* * 打印: * 333 * 222 * 666 * 999 */ // 上源码 ;(function
(global) { global.Promise = Promise // 定义promise三种状态 const PENDING = 'pending'
const FULFILLED = 'fulfilled' const REJECTED = 'rejected' function Promise(fn) {
this.state = PENDING this.fulfilledQueue = [] this.rejectedQueue = [] try { fn(
// 此处需注意this指向 (res) => { this._resolve(res) }, (err) => { this._reject(err) }
// 或者this.resolve.bind(this), this.reject.bind(this)) ) } catch (e) { reject(e)
} } Promise.prototype = { constructor: Promise, _resolve: function (value) { if
(value instanceof Promise) { return value.then( // 此处需注意this指向 (res) => { this.
_resolve(res) }, (err) => { this._reject(err) } ) } setTimeout(() => { if (this.
state=== PENDING) { this.state = FULFILLED this.value = value this.
fulfilledQueue.forEach((fn) => fn(this.value)) } }) }, _reject: function (value)
{ setTimeout(() => { if (this.state === PENDING) { this.state = REJECTED this.
value= value this.rejectedQueue.forEach((fn) => fn(this.value)) } }) }, then:
function (fulfilled, rejected) { this.fulfilled = typeof fulfilled ===
'function' ? fulfilled : (v) => v this.rejected = typeof rejected === 'function'
? rejected : (err) => { throw err } if (this.state === PENDING) { return new
Promise((resolve, reject) => { this.fulfilledQueue.push(() => { try { this.value
= this.fulfilled(this.value) resolve(this.value) } catch (error) { reject(error)
} }) this.rejectedQueue.push(() => { try { this.value = this.rejected(this.value
) resolve(this.value) } catch (error) { reject(error) } }) }) } if (this.state
=== FULFILLED) { return new Promise((resolve, reject) => { setTimeout(() => {
try { this.value = this.fulfilled(this.value) resolve(this.value) } catch (error
) { reject(error) } }) }) } if (this.state === REJECTED) { return new Promise((
resolve, reject) => { setTimeout(() => { try { this.value = this.rejected(this.
value) resolve(this.value) } catch (error) { reject(error) } }) }) } }, } })(
window)

技术
©2019-2020 Toolsou All rights reserved,
JVM内存模型(面试自用)2021年2月中国编程语言排行榜【操作系统----Linux】常用杀毒软件详解ubuntu14.04如何设置静态IP排序(一)冒泡排序法JS 的骚操作漫画 | CPU战争40年,真正的王者终于现身!python中解决字典写入列表的问题C语言控制台小游戏,打砖块SpringBoot实践(五):mybatis-plus中的BaseMapper,Iservice和ServiceImpl