Await javascript recursive function to return true

Viewed 1650

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!

2 Answers

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

Instead use this npm module,
https://www.npmjs.com/package/sync-request

    var request = require('sync-request');
    var res = request('GET', 'http://example.com');
    console.log(res.getBody());
    console.log("Done!")

All the statements will be executed one after another after completion.
Lesser code i guess!!

Related