Sending An Event From A Workflow


# Sending an event to other workflows

The this.select function is used to target other workflows and send them an event from the handle or onEvent generator functions.

For exemple:


module.exports.handle = function* (...) {
  ...
  this.select.workflow().withId("<id>").send("<event name>", ...<event data>);
  ...
};

The ability to communicate between workflows with events is a very powerful feature that allow sophisticated behavior - such as synchronization between workflows (eg. see sequential workflows)

# Sending an event to itself

As a shortcut, a workflow can directly send an event to itself with:

module.exports.handle = function* (...) {
  ...
  this.send("<event name>", ...<event data>);
  ...
};

Below, we use this to wait for 3 different events (3 documents to be received) before continuing:

module.exports.handle = function* (...) {
  ...
  if (this.allDocReceived !== true) {
    yield this.wait.event("allDocsReceived").forever();
  }
  ...
}

module.exports.onEvent = function* (eventName, ...eventData) {
  if (eventName === "doc1Received") {
    this.doc1Received = true;
  }
  if (eventName === "doc2Received") {
    this.doc2Received = true;
  }
  if (eventName === "doc3Received") {
    this.doc3Received = true;
  }
  if (this.this.doc1Received && this.doc2Received && this.doc3Received) {
    this.allDocReceived = true;
    this.send("allDocsReceived");
  }
}