How do I resolve individual promise from a centralized listener?

前端 未结 1 603
野的像风
野的像风 2021-01-20 00:26

I have an event listener, which will receive event (from server) whenever a specific task is done. I desire each task to be encapsulated in a promise, so that I can construc

相关标签:
1条回答
  • 2021-01-20 00:55

    Yes, you'd need a global mapping from ids to resolver functions.

    const tasks = new Map;
    function runTask(id, data) {
        return new Promise(resolve => {
            // if (tasks.has(id)) throw new Error("cannot run multiple "+id+" at once");
            tasks.set(id, resolve);
            client.fire('start', id, data); // or whatever you need to trigger the task
        })
    }
    client.on('taskFinished', event => { // or however you get notified of finished tasks
        const id = event.taskId;
        if (tasks.has(id)) {
            tasks.get(id)(event.result);
            tasks.delete(id);
        }
    });
    

    You can also use a plain object instead of the ES6 Map if you prefer (or need ES5 compatibility), and you might write the listener so that it is only active when the mapping is not empty.

    You would use this like

    runTask('id-1').then(result =>
        runTask('id-2', result)
    ).then(() => {
        console.log("both done");
        return true;
    })
    
    0 讨论(0)
提交回复
热议问题