缺点:Callback Hell 最大的问题真的不过就是不好写切不好看所衍生出来的不好管理罢了,但是代码却是要给人看给人维护给人管理的啊。于是大家就开始绞尽脑汁想办法
**
实例对象 & 函数对象
function Fn(){ // Fn函数
consol.log(0)
}
let fn = new Fn() // Fn 是构造函数 也是函数对象 本身就是对象 fn是实例对象(简称函数)
01.手写promise全过程
js中进行异步变成的新的解决方案;
语法上是一个构造函数,功能上来说promise对象用来封装一个异步操作并可以获取异步操作的结果;
自己的手写的promise的操作,还差的是promise.all 和promise.race函数
class mypromise {
constructor(extour) {
super(extour)
this.statu = 'pending'
this.value = null
this.taskgroup = []
this._rejected = this._rejected.bind(this)
this._resolved = this._resolved.bind(this)
try {
extour(_resolved, _rejected)
} catch (error) {
this._rejected(error)
}
}
_rejected(value) {
setTimeout(() => {
this.statu = 'reject'
this.value = value
// 如果异步.then 数据先一步执行需要吧异步的数据添加到队列中去
if (this.taskgroup.length > 0) {
this.taskgroup.forEach((_resolved, _rejected) => _rejected(value))
}
})
}
_resolved(value) {
setTimeout(() => {
this.statu = 'fullfilled'
this.value = value
// 如果异步.then 数据先一步执行需要吧异步的数据添加到队列中去
if (this.taskgroup.length > 0) {
this.taskgroup.forEach((_resolved, _rejected) => _resolved(value))
}
})
}
_then(_onresolved, _onrejected) {
// 指定默认传入参数必须为函数
_onresolved = typeof _onresolved === 'function' ? _onresolved : (value) => value
_onrejected = typeof _onrejected === 'function' ? _onrejected : (reason) => { throw reason }
const statuCode = this.statu
return new mypromise((_resolved, _rejected) => {
const hander = function (fun) {
try {
const res = fun()
if (res instanceof mypromise) {
// res._then(_resolved, _rejected)
res._then(() => {
(value) => _resolved(value), (reason) => _rejected(reason)
})
} else {
_resolved(res)
}
} catch (error) {
_rejected(error)
}
}
if (statuCode === 'fullfilled') {
setTimeout(() => {
hander(_onresolved)
})
} else if (statuCode === 'reject') {
setTimeout(() => {
hander(_onrejected)
})
} else {
this.taskgroup.push({
_resolved() {
hander(_onresolved)
},
_rejected() {
hander(_onrejected)
},
})
}
})
}
// 函数只要有错误就报错
_catch(onRejected) {
return this._then(null, onRejected)
}
static _resolved(value) {
// 如果返回值是一个成功的promise 那么返回就是这个 成功的value
// 如果返回值是一个失败的promise 那么返回就是这个reason的reason
return new mypromise((_resolved, _rejected) => {
try {
// 判断返回的value是否是mypromise的实例
if (value instanceof mypromise) {
value._then(_resolved, _rejected)
} else {
// 如果接受一个一般值,那么对于返回的是成功的值;返回的值就是这个一般值
_resolved(value)
}
} catch (error) {
_rejected(error)
}
})
}
static _rejected(reason) {
// 只会返回错误的reason
return new mypromise((_resolved, _rejected) => {
_rejected(reason)
})
}
// 多个异步并行和串行
static all(reason) {
}
static race(promises) {
return new mypromise((_resolved, _rejected) => {
promises.forEach((item)=>{
value = {_resolved(item)},
reason = {_rejected(item)}
})
})
}
}
// 测试
new MyPromise((resolve) => {
setTimeout(() => {
resolve(1);
}, 500);
}).then((res) => {
console.log(res);
return new MyPromise((resolve) => {
setTimeout(() => {
resolve(2);
}, 500);
});
}).then((res) => {
console.log(res);
throw new Error('a error')
}).catch((err) => {
console.log('==>', err);
})
JavaScript 在设计阶段为了保证线程安全并且保证引擎不会被 IO 等待所阻塞导致页面失去响应,于是就向其他 GUI 程序学习了“异步事件模型”,所以“异步事件模型” 是一种解决多线程并行问题的模型。
注】其实所谓的 “异步” 并不是 JavaScript 所独有的,而是一种非常成熟和非常古老的模型,并广泛用用在电子电路的设计上。计算机各种附属 IO 设备,尤其是慢速 IO (比如硬盘),都有异步事件响应的设计的影子。
02.真正消灭 callback 的 generator 和 async/await
03.异步串行 | 异步并行
/**
* 关键点
* 1. new promise 一经创建,立即执行
* 2. 使用 Promise.resolve().then 可以把任务加到微任务队列,防止立即执行迭代方法
* 3. 微任务处理过程中,产生的新的微任务,会在同一事件循环内,追加到微任务队列里
* 4. 使用 race 在某个任务完成时,继续添加任务,保持任务按照最大并发数进行执行
* 5. 任务完成后,需要从 doingTasks 中移出
*/
function limit(count, array, iterateFunc) {
const tasks = []
const doingTasks = []
let i = 0
const enqueue = () => {
if (i === array.length) {
return new Promise.resolve()
}
const task = new Promise.resolve().then(() => iterateFunc(array[i++]))
tasks.push(task)
const doing = task.then(() => doingTasks.splice(doingTasks.indexOf(doing), 1))
doingTasks.push(doing)
const res = doingTasks.length >= count ? new Promise.race(doingTasks) : new Promise.resolve()
return res.then(enqueue)
};
return enqueue().then(() => new Promise.all(tasks))
}
// test
const timeout = i => new Promise(resolve => setTimeout(() => resolve(i), i))
limit(2, [1000, 1000, 1000, 1000], timeout).then((res) => {
console.log(res)
})