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
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;
})