javascriptnode.jsnode-fetch

Retry fetch request doesn't return anything


This is the current code and what I've come up with:

function getToken() {
    return new Promise(async (resolve, reject) => {
        try {
            let res = await fetch(url);

            if (res.status === 418) {
                setTimeout(getToken, 1000);
            } else {
                let token = await res.text();
                console.log("1", token);
                resolve(token);
            }
        } catch(e) {
            reject(e);
        }
    });
}

async function test() {
    let token = await getToken();
    console.log("2", token);
}

test();

It logs 1 <token> but it doesn't log the other part like its supposed to (2 <token>). Is there something I'm missing or doing wrong?


Solution

  • My very naive approach would be a mix of a "sleep" function and standard async/await syntax (no need to mix then into it).

    This does not take into consideration a possible infinite loop if the URL consistently returns a 418 http code.

    The biggest thing to note is that I am returning getToken() in the retry and also returning token in the else. If we don't do this token inside test will always be undefined.

    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
    
    async function getToken() {
      try {
        let res = await fetch('https://httpstat.us/200');
    
        if (res.status === 418) {
          await sleep(1000);
          return getToken();
        } else {
          let token = await res.text();
          console.log("1", token);
          return token;
        }
      } catch (e) {}
    };
    
    async function test() {
      let token = await getToken();
      console.log("2", token);
    }
    
    test();