Home > OS >  Variable of function always returns undefined
Variable of function always returns undefined

Time:12-29

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"
    

CodePudding user response:

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))
  • Related