flow.after()

The flow.after() method is used to schedule a callback, usually one that triggers the flow itself, allowing for more sequentially-written code.

Syntax

flow.after(callback);

Parameters

callback
A function to run after the flow has been set up and an await expression has attached its .then() handler internally.

Return value

The same Flow object the method was called on.

Examples

The .after() method is primarily useful in situations where there is a need to await a Flow, but something needs to trigger the flow in question. It can be unreliable to run the code that triggers the flow before it is set up, because the flow might have already triggered before the await expression has been reached. To solve this issue, we can run the triggering code inside the .after() callback, causing it to run only after it is safe to do so.

Loading an image

When loading an image, we'll need to create the image, then set the source, and wait for the load event (for which we'll use when()). However, if we set the image's .src before our await expression, then (if the image is cached) the load event potentially fires before the listener has been set up properly, which results in our code getting stuck on the await. The solution is using .after(), like so:

const img = document.createElement('img'); await when(img).loads().once().after(() => { img.src = './bonfire.webp'; });

This way, we are guaranteed to receive the load event after the flow created by when() has been set up. Additionally, our code is in a more intuitive order since the when() expression should be run before the img.src is set.

See also