Search code examples
node.jstypescriptasynchronousnode-fetch

TypeScript: type for returning an async function call inside a setTimeout()?


I have a function for fetching credentials for an external API (oversimplified):

const fetchCredentials= async () => {
  return await fetch(/* url and params */);      
};

And another one which calls the above and keeps retrying to call if it the response is not ok.

const retryFetchCredentials = (initialDelay = 250): Promise<Credentials | void> => {
    
    return fetchCredentials().then(async res => {    
      if (res.ok) {
        const parsedResponse = await res.json() as Credentials ;
        return parsedResponse;
      }
      else {

        // The issue is with this timeout/return:
        setTimeout(() => { 
          return retryFetchCredentials (initialDelay * 2);
        }, initialDelay);

      }        
    });
};

My problem is that I don't know how to strongly type the return inside the setTimeOut function, I keep getting a Promise returned in function argument where a void return was expected. error. I have tried several return types for the functionretryFetchCredentials to no avail.

Any clues about how to solve this?


Solution

  • Just removing the return from the the function inside setTimeout should make the error go away without affecting the behavior of the rest of the code.

    As a side note, you shouldn't mix async/await with .then for consistency. And if you use async/await whenever possible, your code is going to increase its readability.