简体   繁体   English

如何从异步函数返回多个值以在另一个函数中使用

[英]how to return multiple values from an asynchronous function to use in another function

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

All async functions return a promise that resolves to whatever value you return from that function.所有async函数都返回一个承诺,该承诺解析为您从该函数return任何值。 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:所以,当你调用authWithLoginAndPassword()你必须要么使用.then()await从承诺得到解决值函数返回:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM