How to call the function again without losing a promise?

2

I'm still new to Node.Js, and I do not know how to do this. In the code below, you'll notice that the readSubscriptions () function is called shortly after the login () function. However, if a login error occurs, I do not do anything to treat it, I wanted to call the login () function again, but if I do this it will not give me a promise problem and end up losing my login session? p>

Is there any way, or standard to follow in such cases?

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!")
        } 
    })
    
asked by anonymous 28.12.2016 / 21:39

1 answer

2

You can use the .catch() method of 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 .catch like this:

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();
    
28.12.2016 / 22:03