Skip to content

Defining Tasks

Charles Demers edited this page Aug 20, 2024 · 3 revisions

Defining Tasks with task()

When a task is performed, it runs the code in the generator arrow task function you passed into task(). (If you're unfamiliar with generator functions and the yield keyword, Mozilla has a good introductory guide).

Using the yield keyword

Much of the power of Tasks is unleashed once you start making use of the yield keyword within generator functions. The yield keyword, when used with a promise, lets you pause execution of your task function until that promise resolves, at which point the task function will continue running from where it had paused.

This example demonstrates how you can yield timeout(1000) to pause execution for 1000 ms (one second). The timeout() helper function, which Houston provides, simply returns a promise that resolves after the specified number of milliseconds.

const waitAFewSeconds = task(function* () {
  setStatus('Gimme one second…');
  yield timeout(1000);
  setStatus('Gimme one more second…');
  yield timeout(1000);
  setStatus('OK, I'm done.');
});

When you yield a promise, the yield expression evaluates to the resolved value of the promise. In other words, you can set a variable equal to a yielded promise, and when the promise resolves, the task function will resume and the value stored into that variable will be the resolved value of the promise.

const myTask = task(function* () {
  setStatus('Thinking…');
  const promise = timeout(1000).then(() => 123);
  const resolvedValue = yield promise;
  setStatus(`The value is ${resolvedValue}`);
});

If you yield a promise that rejects, the task function will throw the rejected value (likely an exception object) from the point in task function where the rejecting promise was awaited. This means you can use try {} catch(e) {} finally {} blocks, just as you would for code that runs synchronously.

const myTask = task(function* () {
  setStatus('Thinking…');

  try {
    yield timeout(1000).then(() => {
      throw 'Ahhhhh!!!!';
    });
    setStatus('This does not get used!');
  } catch (error) {
    setStatus(`Caught value: ${error}`);
  }
});
Clone this wiki locally