* Executes a Workflow and waits for the results with exponential backoff. * @param {string} projectId The Google Cloud Project containing the workflow * @param {string} location The workflow location * @param {string} workflow The workflow name * @param {string} searchTerm Optional search term t
( projectId: string, location: string, workflow: string, searchTerm: string )
| 39 | * @param {string} searchTerm Optional search term to pass to the Workflow as a runtime argument |
| 40 | */ |
| 41 | async function executeWorkflow( |
| 42 | projectId: string, |
| 43 | location: string, |
| 44 | workflow: string, |
| 45 | searchTerm: string |
| 46 | ) { |
| 47 | /** |
| 48 | * Sleeps the process N number of milliseconds. |
| 49 | * @param {Number} ms The number of milliseconds to sleep. |
| 50 | */ |
| 51 | function sleep(ms: number): Promise<unknown> { |
| 52 | return new Promise(resolve => { |
| 53 | setTimeout(resolve, ms); |
| 54 | }); |
| 55 | } |
| 56 | const runtimeArgs = searchTerm ? {searchTerm: searchTerm} : {}; |
| 57 | // [START workflows_api_quickstart_execution] |
| 58 | // Execute workflow |
| 59 | try { |
| 60 | const createExecutionRes = await client.createExecution({ |
| 61 | parent: client.workflowPath(projectId, location, workflow), |
| 62 | execution: { |
| 63 | // Runtime arguments can be passed as a JSON string |
| 64 | argument: JSON.stringify(runtimeArgs), |
| 65 | }, |
| 66 | }); |
| 67 | const executionName = createExecutionRes[0].name; |
| 68 | console.log(`Created execution: ${executionName}`); |
| 69 | |
| 70 | // Wait for execution to finish, then print results. |
| 71 | let executionFinished = false; |
| 72 | let backoffDelay = 1000; // Start wait with delay of 1,000 ms |
| 73 | console.log('Poll every second for result...'); |
| 74 | while (!executionFinished) { |
| 75 | const [execution] = await client.getExecution({ |
| 76 | name: executionName, |
| 77 | }); |
| 78 | executionFinished = execution.state !== 'ACTIVE'; |
| 79 | |
| 80 | // If we haven't seen the result yet, wait a second. |
| 81 | if (!executionFinished) { |
| 82 | console.log('- Waiting for results...'); |
| 83 | await sleep(backoffDelay); |
| 84 | backoffDelay *= 2; // Double the delay to provide exponential backoff. |
| 85 | } else { |
| 86 | console.log(`Execution finished with state: ${execution.state}`); |
| 87 | console.log(execution.result); |
| 88 | return execution.result; |
| 89 | } |
| 90 | } |
| 91 | } catch (e) { |
| 92 | console.error(`Error executing workflow: ${e}`); |
| 93 | } |
| 94 | // [END workflows_api_quickstart_execution] |
| 95 | } |
| 96 | |
| 97 | executeWorkflow(projectId, location, workflowName, searchTerm).catch( |
| 98 | (err: Error) => { |