Skip to content
Advertisement

Variable of function always returns undefined

The idea:
I want to return a variable from a function and then output it using console.log().

The problem:
I can’t just use return result because then nothing is returned.
I don`t really know how else to return the variable.

I have already looked at SO posts like this one, however I probably lack suitable understanding to implement this into my code.

The current code

function getPassword(username) {
    const password = keytar.getPassword(service, username) // Function from keytar lib
    password.then((result) => {
        console.log(result)         // Prints password
        return result               // Doesn't return anything
    })
}

pw = getPassword("Name")

// Exemplary, will be replaced by display in Div
console.log(pw)                     // Outputs "undefined"
    

Advertisement

Answer

function getPassword(username) {
    const password = keytar.getPassword(service, username) // Function from keytar lib
    // don't forget to return promise
    return password.then((result) => {
        console.log(result)         // Prints password
        return result               // Doesn't return anything
    })
}

getPassword("Name").then(result => console.log(result))
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement