js-csp / js-csp

CSP channels for Javascript (like Clojurescript's core.async, or Go)
2.33k stars 122 forks source link

External termination of goroutines #125

Open sh4r1k7 opened 7 years ago

sh4r1k7 commented 7 years ago

As discussed in https://github.com/ubolonton/js-csp/issues/77, I too am in need of a .kill() method to dispense with unnecessary alts or control var checking in every goroutine.

As the above PR was closed because the OP was no longer interested I'd like to reopen discussion for this feature - but am not particularly interested in the other features of that PR.

What would it take? Happy to help.

gt3 commented 7 years ago

need of a .kill() method to dispense with unnecessary alts or control var checking in every goroutine.

@Cpt0r Could you provide a concise code snippet to better understand your use case?

hung-phan commented 7 years ago

This is an example

// pretend `go` returns a Process handle instead of a channel
let proc = go(function * () {
  setState({ word: "Connecting in a moment..." });

  yield csp.timeout(500);  

  let ws;
  try {
    ws = new WebSocket("http://wat.com");
    setState({ word: "Connecting now..." });

    yield makeOnConnectChannel(ws);

    setState({ word: "Connected!" });

    let chan = makeMessageChannel(ws);
    while (true) {
      let value = yield chan;
      setState({ word: `Got message: ${value}` });
    }
  } finally {
    ws.close();
    setState({ word: "Disconnected!" });
    // ...and any other cleanup
    // this block would be invoked upon termination
    // (a lesser known fact about generators is that calling .throw/.return
    // on them will still run finally blocks and even let you yield additional values before closing)
  }
});

// later, after user presses a button, or leaves a route
proc.kill();