js購読リリースモード

1584 ワード

要求:fetch 1=>fetch 2=>fetch 3を順次実行し、fetch 1の結果をfetch 2のパラメータとし、fetch 2の結果をfetch 3のパラメータとします.
interface IEvents {
    [key: string]: Array
}

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()