# Persisting and cancelling workflows

This page explains how to persist a workflow for later restoration and how to cancel its execution while it is running.

## Persisting workflows

You can save a workflow ID to retrieve its result later. This is especially useful for long-running automations that might be interrupted by an application restart.

The process involves these steps:

1. When you initiate a workflow with `execute()`, save the returned `workflowId`.
2. After a restart, retrieve the saved `workflowId`.
3. Call the `result()` method on the same SDK method, passing the saved `workflowId` to get the result.

```typescript
// --- Step 1 & 2: Initiate a workflow and save its references ---

async function startAndSaveWorkflow(taskId) {
  try {
    const { workflowId } = await linkedapi.checkConnectionStatus.execute({
      personUrl: "https://www.linkedin.com/in/john-doe"
    });

    // Save the workflow ID to your database
    await db.saveTask({
      taskId: taskId,
      workflowId: workflowId
    });

    console.log(`Workflow ${workflowId} started and saved for task ${taskId}.`);
  } catch (e) {
    console.error('Failed to start workflow:', e.message);
  }
}

// --- Step 3 & 4: Restore the workflow and get the result ---

async function restoreAndGetResult(taskId) {
  try {
    // Retrieve the saved workflow ID from your database
    const task = await db.getTask(taskId);
    if (!task || !task.workflowId) {
      console.log(`No pending workflow found for task ${taskId}.`);
      return;
    }

    // Get the result using the saved workflow ID
    // You call the same method you used to start the workflow
    const { data, errors } = await linkedapi.checkConnectionStatus.result(task.workflowId);

    if (data) {
      console.log(`Task ${taskId} complete. Result:`, data);
      await db.updateTaskStatus(taskId, 'complete');
    }
  } catch (e) {
    console.error(`Failed to get result for task ${taskId}:`, e.message);
    await db.updateTaskStatus(taskId, 'failed');
  }
}
```

```python
from linkedapi import CheckConnectionStatusParams, LinkedApiError

# --- Step 1 & 2: Initiate a workflow and save its references ---

def start_and_save_workflow(task_id):
    try:
        workflow = linkedapi.check_connection_status.execute(
            CheckConnectionStatusParams(person_url="https://www.linkedin.com/in/john-doe")
        )

        # Save the workflow ID to your database
        db.save_task(task_id=task_id, workflow_id=workflow.workflow_id)

        print(f"Workflow {workflow.workflow_id} started and saved for task {task_id}.")
    except LinkedApiError as e:
        print("Failed to start workflow:", e.message)


# --- Step 3 & 4: Restore the workflow and get the result ---

def restore_and_get_result(task_id):
    try:
        # Retrieve the saved workflow ID from your database
        task = db.get_task(task_id)
        if not task or not task.workflow_id:
            print(f"No pending workflow found for task {task_id}.")
            return

        # Get the result using the saved workflow ID
        # You call the same method you used to start the workflow
        result = linkedapi.check_connection_status.result(task.workflow_id)

        if result.data:
            print(f"Task {task_id} complete. Result:", result.data)
            db.update_task_status(task_id, "complete")
    except LinkedApiError as e:
        print(f"Failed to get result for task {task_id}:", e.message)
        db.update_task_status(task_id, "failed")
```

## Cancelling workflows

You can cancel any running workflow when you no longer need its results. This is useful for stopping long-running automations or when conditions in your application change.

To cancel a workflow, call the `cancel()` function with the `workflowId`:

```typescript
// --- Start a workflow and then cancel it ---
async function startAndCancelWorkflow() {
  try {
    // Step 1: Initiate the workflow
    const { workflowId } = await linkedapi.checkConnectionStatus.execute({
      personUrl: "https://www.linkedin.com/in/john-doe"
    });

    console.log(`Workflow ${workflowId} started.`);

    // Step 2: Cancel the workflow using its ID
    // You call cancel() on the same method you used to start the workflow
    const result = await linkedapi.checkConnectionStatus.cancel(workflowId);

    if (result.cancelled) {
      console.log(`Workflow ${workflowId} cancelled successfully.`);
    }
  } catch (e) {
    console.error('Failed to process workflow:', e.message);
  }
}
```

```python
from linkedapi import CheckConnectionStatusParams, LinkedApiError

# --- Start a workflow and then cancel it ---
def start_and_cancel_workflow():
    try:
        # Step 1: Initiate the workflow
        workflow = linkedapi.check_connection_status.execute(
            CheckConnectionStatusParams(person_url="https://www.linkedin.com/in/john-doe")
        )

        print(f"Workflow {workflow.workflow_id} started.")

        # Step 2: Cancel the workflow using its ID
        # You call cancel() on the same method you used to start the workflow
        cancelled = linkedapi.check_connection_status.cancel(workflow.workflow_id)

        if cancelled:
            print(f"Workflow {workflow.workflow_id} cancelled successfully.")
    except LinkedApiError as e:
        print("Failed to process workflow:", e.message)
```

**Important notes:**

- **Partial execution.** The workflow is cancelled at its current execution point. Any actions that have already been completed cannot be undone. For example, if the workflow has already sent messages or connection requests from your LinkedIn account, these actions will remain executed.
- **No intermediate data.** Once a workflow is cancelled, no data is preserved or returned. You will not receive any intermediate results or partial data that may have been collected before cancellation.
