常言道:“知其然,更要知其所以然”
所谓JS本身是“函数式,异步”编程(回调地狱,你懂的),Promise得出现,让JS写起来好像是“同步编程”得感觉了!
下面是基于我自己对Promise得理解,用ES6语法写了一个Promise
// 既然Promise使用得时候是通过new得到的,那么首先分析出Promise是一个类
class Promise2 {
// Promise接收一个回调函数作为参数,这里将回调函数fn传入构造中
constructor (fn) {
let _this = this
this.success_res = null // success_res保存的是“成功回调” -> resolved执行时候传递得结果
this.error_res = null // error_res保存的是“失败回调” -> rejected执行时候传递的结果
/**
* Promise的核心重点就在于“状态”
* 如果操作结果还没有成功或者失败,那么then传进来的两个回调函数,就会被“挂起”
*/
this.state = 'pending' // 还没得到成功或失败的结果状态
this.fnArr = [] // 保存挂起的回调函数 -> 外部调用then时传进来的回调函数,这里将它们“队列”起来
function resolved (...args) { // 如果传入的值是多个,那么直接用...运算符“打包”
_this.success_res = args // 记录成功得到的数据
_this.state = 'success' // 改变状态
_this.fnArr.forEach(json => json.success(_this.success_res)) // 执行“挂起”的成功回调
}
function rejected (...args) {
_this.error_res = args
_this.state = 'error'
_this.fnArr.forEach(json => json.error(_this.error_res))
}
fn(resolved, rejected) // 将成功、失败两个回调传回给调用处
}
/**
* then是根据状态,控制下一步该怎么做的关键
* 成功、失败都会执行对应的回调,并且回传结果
* 那么当没有结果时候怎么办呢?直接挂起即可
* 挂起后的函数什么时候执行呢?成功、失败的时候,直接去挂起的“队列”中取出来,并且执行
*/
then (success, error) {
if (this.state === 'success') success(this.success_res)
if (this.state === 'error') error(this.error_res)
if (this.state === 'pending') this.fnArr.push({ success, error })
}
}
好啦小伙伴们,我们来试着用一用 o( ̄▽ ̄)o
new Promise2((resolved, rejected) => {
setTimeout(() => {
resolved('success')
}, 1000)
// rejected('error')
})
.then(res => {
console.log(res)
}, err => {
console.log(err)
})
控制台打印出了这么个东西,是个数组没错,因为我的Promise支持传多个参数 ( ̄▽ ̄)"
总结一下
Promise的本质就是一种 状态管理机制
我是如何理解并且手写出来一个自己的Promise的?首先我想说说对js函数式编程的理解。
异步函数式编程的核心在于“将函数当作函数的参数传递”
,是不是有点绕?(●ˇ∀ˇ●)
如果你对函数的“传递”理解的深了,那么恭喜你!你会对js这种回调函数式编程有了更高一层的认识
场景意淫 -> “封装后的函数,方法怎么用”?
php程序员:“传递参数”
java程序员:“传递参数+传递类型(泛型)”
javascriptER: “函数里面传函数”
( ̄▽ ̄)"