console.log with values and return undefined

0
var got = require('got')
exports.coger = function (id){
let i;
if (!id){
    i = "Introduzca una id";
    return i;
}
got('enlace privado').then(f => {
    let a = JSON.parse(f.body)
    console.log(a)
    if(a.error){
       i = a.error
        return i;
    }
    i ={"usuario":a.usuario,"id":a.id,"descripcion":a.descripcion,"fecha":a.fecha,"multicuentas":a.multicuentas}
    return i;
})

}

I have also tried to put the return i ; out of}} but still giving undefined everything works fine except the ending since doing return i ; it tells me undefined instead of object i

    
asked by seyron 13.08.2018 в 12:26
source

1 answer

1

When you do not pass a id function coger gives you an immediate result. In another case, call a function that returns a promise and until that promise is not resolved, i remains undefined.

You should handle it by always returning a promise:

var got = require('got')
exports.coger = function (id) {

    let i;
    if (!id) {
        return Promise.reject(new Error("Introduzca una id"));
    }
    return got('/enlace/${id}').then(f => {
        let a = JSON.parse(f.body)
        console.log(a)
        if (a.error) {
            return Promise.reject(new Error(a.error));
        }
        i = {
            "usuario": a.usuario,
            "id": a.id,
            "descripcion": a.descripcion,
            "fecha": a.fecha,
            "multicuentas": a.multicuentas
        }
        return i;
    });

}

And then call coger managing your result with then/catch

coger(id).then((res)=>{
    console.log('Resultado: ', res);
}).catch((err)=>{
    console.log('Error: ',err);
});

From what I see in your code, it may be the case that a request is successful but the response contains an error message, so I included an explicit error that will be intercepted by your catch in that circumstance. Other errors in the same request will go to the catch but with a different message.

    
answered by 13.08.2018 в 13:24