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

liaoxinyu
35 声望5 粉丝

前端开发.