关于javascript:js订阅发布模式

48次阅读

共计 925 个字符,预计需要花费 3 分钟才能阅读完成。

要求:顺次执行 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()

正文完
 0