Waiting for Events
Introduction
This example demonstrates how to handle order processing using Upstash Workflow. The workflow will wait for an external system to process an order and resume once it is ‘notified’. See our documentation for more details about events.
Use Case
Our workflow will be:
- Receive an order request.
- Send an email to request order processing.
- Wait for an external event that indicates the order has been processed.
- Handle timeout scenarios if the event is not received in time.
- Save the results
Code Example
Code for notifying the worklfow:
Code Breakdown
1. Requesting Order Processing
In its first step, we call a method to request processing of the order in the request payload:
You can imagine that this step sends an email to the company responsible for the delivery.
2. Waiting for the Event
Next, the workflow waits for the order to be processed. It uses the waitForEvent
method to pause execution and listen for the event. A timeout of 10 minutes (600 seconds) is applied to avoid indefinite waiting.
The workflow listens for the event with the ID order-${orderId}
. When the external service notifies the workflow with this ID, the workflow resumes. If no event is received in time, the timeout ensures the workflow doesn’t hang.
3. Processing the Order
Once the workflow resumes, the order data (eventData
) is logged. This step could include updates to the database, inventory adjustments, or other backend operations specific to order processing.
4. Sending a Confirmation Email
Once the order is processed, the workflow sends a confirmation email to the user.
External Event Notification
To notify the workflow that the order has been processed, the external system sends a notification to the workflow with relevant data using the notify
method from the Client
. Alternatively, you can use context.notify
method.
Key Features
- Asynchronous Event Handling: The workflow waits for an external event (order processing) to occur and only resumes once the event is received.
- Timeout Control: A timeout mechanism ensures that the workflow doesn’t hang if the event isn’t received within the expected time.
- Order Processing: Once notified, the workflow handles order processing and sends a confirmation email to the customer.
- External Event Notifications: The external system can notify the workflow, providing the necessary data to resume execution and complete the process.
Was this page helpful?