withTask()

Wrap an async function as a traced task

Overview

Use withTask(options, fn) to mark a discrete step within a workflow. Tasks are automatically linked to their parent workflow or agent.

Signature

1withTask<T>(
2 options: {
3 name: string;
4 version?: number;
5 associationProperties?: Record<string, any>;
6 },
7 fn: () => Promise<T>
8): Promise<T>

Basic Usage

1import { RespanTelemetry } from '@respan/tracing';
2
3const respanAi = new RespanTelemetry({
4 apiKey: process.env.RESPAN_API_KEY,
5 appName: 'my-app'
6});
7
8await respanAi.initialize();
9
10const result = await respanAi.withTask(
11 { name: 'data_processing' },
12 async () => {
13 const data = await fetchFromDatabase();
14 return processData(data);
15 }
16);

With Metadata

1await respanAi.withTask(
2 {
3 name: 'api_call',
4 version: 2,
5 associationProperties: {
6 'endpoint': '/api/users',
7 'method': 'GET'
8 }
9 },
10 async () => {
11 return await fetch('https://api.example.com/users');
12 }
13);

Within a Workflow

1await respanAi.withWorkflow(
2 { name: 'user_onboarding' },
3 async () => {
4 await respanAi.withTask(
5 { name: 'create_account' },
6 async () => {
7 return await createUserAccount();
8 }
9 );
10
11 await respanAi.withTask(
12 { name: 'send_welcome_email' },
13 async () => {
14 return await sendEmail();
15 }
16 );
17
18 return 'onboarding_complete';
19 }
20);

Error Handling

1try {
2 await respanAi.withTask(
3 { name: 'risky_operation' },
4 async () => {
5 const result = await riskyApiCall();
6 return result;
7 }
8 );
9} catch (error) {
10 // Error is automatically recorded in the span
11 console.error('Task failed:', error);
12}

Parameters

name
stringRequired

Task display name for identification in the Respan dashboard

version
number

Version number for tracking task iterations

associationProperties
Record<string, any>

Custom metadata to associate with the task

Return Value

Returns a Promise that resolves to the return value of the provided function.

Best Practices

  • Use tasks for discrete, measurable operations within workflows
  • Name tasks clearly to reflect their purpose
  • Nest tasks within workflows or agents for proper hierarchy
  • Tasks automatically capture timing and error information