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)
})
0

1 Answer 1

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);
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.