js订阅发布模式
Posted liaoxinyu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js订阅发布模式相关的知识,希望对你有一定的参考价值。
要求:依次执行fetch1=>fetch2=>fetch3,先执行fetch1,需要将fetch1的结果作为fetch2的参数,fetch2的结果作为fetch3的参数。
interface IEvents {
[key: string]: Array<Function>
}
class EventListener {
events: IEvents
constructor() {
this.events = {}
}
listen(key, fn) {
let fns = this.events[key];
if (fns) {
fns.push(fn)
} else {
this.events[key] = [fn]
}
}
on(key, payload) {
const fns = this.events[key]
if (fns && fns.length > 0) {
const fn = fns.shift()
fn(payload)
}
}
remove(key, fn) {
const fns = this.events[key]
if (!Array.isArray(fns)) return
const index = fns.indexOf(fn)
if (index !== -1) {
fns.splice(index, 1)
}
}
}
let listener = new EventListener()
const fetch1 = () => {
setTimeout(() => {
const res = {
current: \'fetch1\',
next: \'fetch2\'
}
console.log(res)
listener.on(\'fetch2\', res)
})
}
const fetch2 = (payload) => {
setTimeout(() => {
const res = {
current: payload.next,
next: \'fetch3\'
}
console.log(res)
listener.on(\'fetch3\', res)
})
}
const fetch3 = (payload) => {
console.log({
current: payload.next,
next: \'\'
})
}
listener.listen(\'fetch2\', fetch2)
listener.listen(\'fetch3\', fetch3)
fetch1()
以上是关于js订阅发布模式的主要内容,如果未能解决你的问题,请参考以下文章