-1

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?

Nitsua
  • 235
  • 2
  • 8

3 Answers3

1

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();

evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
0
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

function get(url, retryStatusCode) {
    return new Promise(async (resolve, reject) => {
        let found = false;
        while (found !== true) {
            try {
                await sleep(1000);
                await fetch(url).then(res => { 
                    let text = res.text(); 
                    let status = res.status;
                    if (status !== retryStatusCode) {
                        found = true;
                        resolve(text);
                    }
                });
            } catch (error) {
                reject(error);
            }
        }
    });
};

Then await get(url, 404).

Nitsua
  • 235
  • 2
  • 8
-1

Use then

await fetch(url).then(res=>console.log(res).catch(err=>console.log(err);

I'm just logging the res here, you can do whatever you want with it

Mohak Gupta
  • 163
  • 1
  • 9