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