Await javascript recursive function to return true

2820 views javascript
8

So I'm using puppeteer in nodeJS and I have a function that recursively calls itself until a specified page is correctly loaded:

const isPageAccessible = async (page, url) => {
    var pageRes = await page.goto(url, {
        timeout: 10000
    }).catch(e => console.log(e));
    if (!pageRes || pageRes.status !== 200) {
        console.log("Website didn't load properly.")
        isPageAccessible(page, url);
    } else {
        console.log("Loaded!")
        return true;
    }
}

The problem here is that this function is returning undefined after the first recursive call (which is normal as far as I know since async functions must resolve with a value). I want the code to wait until this function resolves with true

console.log(await isPageAccessible(page,LOGIN_URL));

console.log("Done!")

So the console would log "Done!" after the website has been loaded succesfully. Right now it is logging "Done!" even if the website hasn't been loaded since isPageAccessible function is returning undefined after the first call.

Any thoughts on how to solve this would be appreciated!

answered question

why not use a loop?

1 Answer

11

You need to return the recursive call up the Promise chain:

if (!pageRes || pageRes.status !== 200) {
  console.log("Website didn't load properly.")
  return isPageAccessible(page, url);
}

posted this

Have an answer?

JD

Please login first before posting an answer.