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

时间:2020-09-14 20:56:26

标签: javascript function asynchronous promise

我正在通过异步函数获取登录名和密码值,并使用解构返回。但是,当我尝试在另一个函数中使用数据时,它输出-未定义。请帮忙。有什么问题

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

1 个答案:

答案 0 :(得分:1)

所有buttons: [ 'copyHtml5', 'excelHtml5', 'csvHtml5', { extend: 'pdf', orientation: 'landscape', exportOptions: { columns: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ] } } ] 函数都返回一个承诺,该承诺将解析为该函数中您async的任何值。因此,当您调用return时,必须使用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);
     }
});