【问题标题】:async/await not working, function returning {"_U": 0, "_V": 0, "_W": null, "_X": null} [duplicate]async/await 不工作,函数返回 {"_U": 0, "_V": 0, "_W": null, "_X": null} [重复]
【发布时间】:2022-02-17 21:28:49
【问题描述】:

我在 StackOverflow 上尝试过其他类似的问题,但没有找到解决问题的方法。

问题是我在函数内部进行 API 调用,我也在使用 async/await 进行此调用,但函数仍然返回 {"_U": 0, "_V": 0, "_W": null, "_X": null}。

通过this 和 StackOverflow 上的其他问题,我了解到这个问题的出现是因为该函数无法与 API 正常工作。

import { firebase } from '@react-native-firebase/firestore';

async function userLogin(name, password) {
    await firebase.firestore().collection('users').where("name", "==", name).where("password", "==", password).get()
        .then((response) => {
            console.log('Response:')
            if (response.docs === []) {
                return
            } else {
                return true
            }
        }).catch(err => console.error(err));
}

const initialState = {
    loggedIn: false,
    name: '',
}

const rootReducer = (state = initialState, action) => {
    if (action.type === 'LogIn') {
        const data = userLogin(action.name, action.password)
        if (data) {
        return {
            ...state,
            name:action.name,
            loggedIn:false
            }
        }
        else {
            console.log(4);
            return {
                ...state,
                name: 'aName',
                loggedIn:true
            }
            }
    }
    return state;
}

export default rootReducer;

【问题讨论】:

  • userLogin 返回一个承诺。 data 包含一个承诺。我认为,你不能在 reducer 中使用异步函数。
  • 除了@jabaa 的评论,尝试在reducer 之外调用userLogin func 并在成功响应时调度登录操作

标签: javascript reactjs react-native asynchronous async-await


【解决方案1】:

userLogin 不会在您的代码中返回任何内容。试试:

async function userLogin(name, password) {
  return await firebase.firestore().collection('users').where("name", "==", name).where("password", "==", password).get()
  ...

准确的说,根据jabaa的评论,userLogin返回了包裹在Promise中的null,看起来像

{“_U”:0,“_V”:0,“_W”:空,“_X”:空}

尝试添加返回,然后检查数据常量。这会给你来自 firestore 方法的响应。

【讨论】:

  • “异步函数总是返回一个promise。如果异步函数的返回值不是显式的promise,它将被隐式地包装在promise中。” developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • 是的,这是真的,但如果你不设置返回值,它会响应 null 包装在 promise 中,就像你的情况一样: {"_U": 0, "_V": 0, “_W”:空,“_X”:空}。这就是为什么 const data = userLogin(action.name, action.password) 将“数据”设置为无效的承诺而不是 firebase 方法响应。
  • 但是你的答案是错误的:“userLogin not return any in your code”userLogin 返回一个承诺。你的回答不能解决问题。 data 仍然是一个承诺。if (data) 不会起作用。
猜你喜欢
  • 2022-01-14
  • 2022-01-05
  • 2021-03-02
  • 2022-01-14
  • 2021-04-21
  • 1970-01-01
  • 2021-11-26
  • 2021-12-20
相关资源
最近更新 更多