1

I am getting login and password values in an asynchronous function and returning using destructuring. But when I try to use the data in another function, it outputs - undefined. Help please. In what the problem

async function authWithLoginAndPassword() {
    const response = await fetch('');
    const data = await response.json();
    const logUser = data[0].login;
    const passwordUser = data[0].password;
    return { logUser, passwordUser }
}
submit.addEventListener('click', () => {
    let register = authWithLoginAndPassword();
    console.log(register.logUser, register.passwordUser)
})
ameli
  • 73
  • 6

1 Answers1

1

All async functions return a promise that resolves to whatever value you return from that function. So, when you call authWithLoginAndPassword(), you have to use either .then() or await to get the resolved value from the promise that the function returns:

submit.addEventListener('click', async () => {
    try {
        let register = await authWithLoginAndPassword();
        console.log(register.logUser, register.passwordUser)
     } catch(e) {
        // catch errors
        console.log(e);
     }
});

or

submit.addEventListener('click', () => {
    authWithLoginAndPassword().then(register => {
        console.log(register.logUser, register.passwordUser)
    }).catch(err => {
        console.log(err);
    });
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979