JueK3y
JueK3y

Reputation: 317

Check two statements simultaneously

The idea:
I am building a bot to log into Instagram using puppeteer.
If the login is successful, nothing happens. When an error with ID slfErrorAlert occurs, the bot stops (because the LogIn was not successful).

The problem:
After pressing the LogIn button, the first and afterwards the second statement is checked.
However, it should be checked at the same time whether one or the other statement is true.
This could be the pseudo code:
If (Login == true) continue;
else if (slfErrorAlert == visible) stop;


Current code snippet

if ((await instagram.page.url() !== loginURL) || (await instagram.page.waitForSelector('#slfErrorAlert'))) {
    if (await instagram.page.url() !== loginURL) {
        log.info("LogIn successfull")
        log.info(instagram.page.url())
    }
    if (await instagram.page.waitForSelector('#slfErrorAlert')) {
        let loginMessage = await instagram.page.$eval('#slfErrorAlert', element => element.innerHTML)
        log.warn(`Client error - LogIn not possible: '${loginMessage}'`)
        await instagram.browser.close()
        return
    }
}

Full code is here: https://github.com/JueK3y/Instagram-automated-commenting/blob/main/public/src/js/instagram.js

Upvotes: 0

Views: 64

Answers (1)

NickG
NickG

Reputation: 601

If i understand you correctly, you want to test both async calls simultaneously. You can do that with the function Promise.race.

let promise1 = instagram.page.url();
let promise2 = instagram.page.waitForSelector('#slfErrorAlert');

Promise.race([promise1, promise2]).then((result) => {
  // do your checks here, either of the 2 promises was resolved
  // the result is either the one return from the first or second promise
}) 

For a detailed explanation and an extended example on how to use it, see MDN web docs: Promise.race()

Upvotes: 2

Related Questions