1.promise如何手写实现
class myPromise{
// 构造器
constructor(excutor){
// 初始化状态为等待
this.state = 'pending'
// 成功的值
this.value = undefined
// 失败的值
this.reason = undefined
// 成功存放的数组
this.onResolvedCallbacks = []
// 失败存放的数组
this.onRejectedCallbacks = []
// 成功
const resolve = (value) => {
// 只有pending状态下才可以更改状态
if(this.state === 'pending'){
this.state = 'fullfilled'
this.value = value
// 一旦resolve执行,调用成功数组的函数
this.onResolvedCallbacks.forEach(fn=>fn())
}
}
// 失败
const reject = (reason) => {
// 只有pending状态下才可以更改状态
if(this.state === 'pending'){
this.state = 'rejected'
this.reason = reason
// 一旦reject执行,调用失败数组里的函数
this.onRejectedCallbacks.forEach(fn=>fn())
}
}
try{
// 立即执行
excutor(resolve,reject)
} catch (err){
reject(err)
}
}
then(onFullfilled,onRejeted){
// 如果状态是fullfilled,则执行onFullfilled,传入成功的值
if(this.state === 'fullfilled'){
onFullfilled(this.value)
}
// 如果状态是rejected,则执行onRejected,传入成功的值
if(this.state === 'rejected'){
onRejeted(this.reason)
}
if(this.state === 'pending'){
// onFullfilled传入成功数组
this.onResolvedCallbacks.push(()=>{onFullfilled(this.value)})
// onRejeted传入失败数组
this.onRejectedCallbacks.push(()=>{onRejeted(this.reason)})
}
}
}
2.promise是怎么解决回调地域问题的
- 异步函数为了保证顺序执行,那么便需要使用嵌套的回调函数方式来实现,这就会引起回调地域
setTimeout(function () {
//第一层 console.log(111);
setTimeout(function () {
//第二程 console.log(222);
setTimeout(function () {
//第三层 console.log(333); }, 1000) }
, 2000) },
3000)
,1000}
- 解决这个问题可以使用promise的.then链式调用
- 但是链式调用太长的话,写法并不优雅易读。这时可以使用async和await来同步化代码执行
3.数组转树并按照weight进行排序
文章里采用了3种方式
前两种是循环遍历,然后直接取改变数组中对象的内容来实现,只需要学会第一种方法即可
第三种方法是递归,也需要学会
events.jianshu.io/p/36c5e4b49…
按照weight排序可以如此
arr.sort((a,b)=>a.weight-b.weight)
4.react的vdom是什么
5.react为什么不建议使用index作为key
- 如果用一个可变list去生成Dom,并用index作为他的key。那么举个例子在最开始的dom前面加上一个dom,第一个dom的index从0变成了1。react的element层级更新会判断这个vdom发生了改变而重新渲染,但其实它没发生改变,这样就造成了性能的消耗