title: Awaited async method keep previous retry payload
body: <p>In our program, we try to implement a task retry pattern with <code>await</code>. </p>
  
  <p>Our main problem is our method keeps the first retry payload in subsequent ones. </p>
  
  <p>Here is the retry method:</p>
  
  <pre><code>async retryTaskUntilExpectedValue({
      task,
      expectedValue,
      messageOnError = 'Max retry number reached without expected result',
      maxRetries = 10,
      timeout = 10,
      spinner = null
    }) {
      let printFn = console.log;
      if (spinner !== null) {
        printFn = spinner.text;
      }
  
      // Proceed retries
      for (let i = 1; i &lt;= maxRetries; i++) {
        try {
          let result = await task;
  
          console.log(result); // Always display same result: {"state": "upgrading"} even if curling returns {"state": "upgraded"} after about 2 retries
  
          result = JSON.parse(result).state;
  
          if (result === expectedValue) {
            return Promise.resolve(result);
          } else if (i &lt;= maxRetries) {
            printFn(`Result "${result}" differs from expected value "${expectedValue}"`);
            await wait(1000);
  
            printFn(`Waiting ${timeout}s before retry`);
            await wait(timeout * 1000);
  
            printFn(`Retrying (${i})`);
            continue;
          } else {
            return Promise.reject(`ERROR: ${messageOnError}`);
          }
        } catch (err) {
          return Promise.reject(`ERROR: Unexpected error while running task`);
        }
      }
  };
  </code></pre>
  
  <p>And the use in our CLI:</p>
  
  <pre><code>checkUpgrade(url) {
      return retryTaskUntilExpectedValue({
        task: this.makeHttpRequest('GET', url),
        expectedValue: 'upgraded'
      });
  }
  </code></pre>
  
  <p>In our case, the task is an http request returning a state from our backend database.</p>
  
  <p>The model is simple:
  <code>{ "state": "upgrading" }</code> then when the backend job is done, it returns <code>{ "state": "upgraded"}</code>.</p>
  
  <p>The job takes some time to process (around 20 sec). In our tests, this behavior occured:</p>
  
  <ul>
  <li>First call: <code>upgrading</code></li>
  <li>First retry: <code>upgrading</code></li>
  <li>After that, by curling directly the REST api by hand, I get the <code>upgraded status</code></li>
  <li>all other retries in the CLI: <code>upgrading</code></li>
  </ul>
  
  <p>So in the CLI we build, we have 10 times the result: <code>Result "upgrading" differs from expected value "upgraded"</code></p>
  
  <p>It seems the <code>let response = await task;</code> in the subsequent retries does not call the task method at each retry. Indeed if actual call was made, it would for sure retrieve the proper upgraded state since we get it through curl.</p>
  
  <p>How to make the <code>await task;</code> to actually trigger the call task method and not to keep the result from first call?</p>