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

withTask<T>(
options: {
name: string;
version?: number;
associationProperties?: Record<string, any>;
},
fn: () => Promise<T>
): Promise<T>

Basic Usage

import { RespanTelemetry } from '@respan/tracing';
const respanAi = new RespanTelemetry({
apiKey: process.env.RESPAN_API_KEY,
appName: 'my-app'
});
await respanAi.initialize();
const result = await respanAi.withTask(
{ name: 'data_processing' },
async () => {
const data = await fetchFromDatabase();
return processData(data);
}
);

With Metadata

await respanAi.withTask(
{
name: 'api_call',
version: 2,
associationProperties: {
'endpoint': '/api/users',
'method': 'GET'
}
},
async () => {
return await fetch('https://api.example.com/users');
}
);

Within a Workflow

await respanAi.withWorkflow(
{ name: 'user_onboarding' },
async () => {
await respanAi.withTask(
{ name: 'create_account' },
async () => {
return await createUserAccount();
}
);
await respanAi.withTask(
{ name: 'send_welcome_email' },
async () => {
return await sendEmail();
}
);
return 'onboarding_complete';
}
);

Error Handling

try {
await respanAi.withTask(
{ name: 'risky_operation' },
async () => {
const result = await riskyApiCall();
return result;
}
);
} catch (error) {
// Error is automatically recorded in the span
console.error('Task failed:', error);
}

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