How to recall the function without losing the Precedent?

Asked

Viewed 308 times

2

I’m still beginner in Node.Js, and do not know how to do this operation. In the code below to realize that the function readSubscriptions() is called right after function login(). But if there is an error in the login() I do not do anything to treat it, I wanted to call the login() function again, but if I do this will not give problem in the file and end up losing my login session?

Is there any way, or pattern to follow in cases like this?

let cs      = require('cloudscraper')
let promise = require('promise')

let login = function() {
    return new promise((resolve, reject) => {
        console.log("Logando...")
        cs.post("https://bj-share.me/login.php", {username: '****', password: '*****', keeplogged: true}, (err) => {
            if (err){
                console.log("Login falhou!\n")
                reject(err)
            } else {
                console.log("Login com sucesso!\n")
                resolve()
            }
        })
    })
}

let readSubscriptions = function(){
    return new promise((resolve, reject) => {
        console.log("Lendo página de seguidos...")
        cs.get("https://bj-share.me/userhistory.php?action=subscriptions", (err, res, body) => {
            if (err){
                console.log("Leitura falhou!\n")
                reject(err)
            } else {
                console.log("Leitura com sucesso!\n")
                resolve(body)
            }
        })
    })
}

login()
    .then(readSubscriptions)
    .then((res) => {
        if (res.indexOf("Nenhum post seguido foi atualizado.") != -1){
            console.log("Não há atualizações!")
        } 
    })
  • Do you want me to test again if login fails? test like this: https://jsfiddle.net/4vwoegmj/1

  • 1

    Oops, it worked! Thanks Sergio!

  • Good! I’ll give you an answer then

1 answer

2


You can use the method .catch() das Promises to start a new action when something goes wrong.

If you create a new function with what you already have you can call it inside the .catch thus:

function ligar() {
    login()
        .then(readSubscriptions)
        .then(res => {
            if (res.includes("Nenhum post seguido foi atualizado.")) {
                console.log("Não há atualizações!")
            }
        }).catch(() => {
            setTimeout(ligar, 1000); // esperar um segundo e tentar de novo
        });
}
ligar();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.