async function executeWorkflow()

in workflows/quickstart/index.js [44:93]


async function executeWorkflow(projectId, location, workflow, searchTerm) {
  /**
   * Sleeps the process N number of milliseconds.
   * @param {Number} ms The number of milliseconds to sleep.
   */
  function sleep(ms) {
    return new Promise(resolve => {
      setTimeout(resolve, ms);
    });
  }
  const runtimeArgs = searchTerm ? {searchTerm: searchTerm} : {};
  // [START workflows_api_quickstart_execution]
  // Execute workflow
  try {
    const createExecutionRes = await client.createExecution({
      parent: client.workflowPath(projectId, location, workflow),
      execution: {
        // Runtime arguments can be passed as a JSON string
        argument: JSON.stringify(runtimeArgs),
      },
    });
    const executionName = createExecutionRes[0].name;
    console.log(`Created execution: ${executionName}`);

    // Wait for execution to finish, then print results.
    let executionFinished = false;
    let backoffDelay = 1000; // Start wait with delay of 1,000 ms
    console.log('Poll every second for result...');
    while (!executionFinished) {
      const [execution] = await client.getExecution({
        name: executionName,
      });
      executionFinished = execution.state !== 'ACTIVE';

      // If we haven't seen the result yet, wait a second.
      if (!executionFinished) {
        console.log('- Waiting for results...');
        await sleep(backoffDelay);
        backoffDelay *= 2; // Double the delay to provide exponential backoff.
      } else {
        console.log(`Execution finished with state: ${execution.state}`);
        console.log(execution.result);
        return execution.result;
      }
    }
  } catch (e) {
    console.error(`Error executing workflow: ${e}`);
  }
  // [END workflows_api_quickstart_execution]
}