gpt4 book ai didi

javascript - 如何在 React-Native 中按顺序运行异步函数?

转载 作者:行者123 更新时间:2023-12-01 01:13:27 25 4
gpt4 key购买 nike

我有一个这样的 Action :

export const loginUser = ({ email, password }) => {
return (dispatch) => {
dispatch({ type: LOGIN_USER });

firebase.auth().signInWithEmailAndPassword(email, password)
.then(user => {
const { currentUser } = firebase.auth();
firebase.database().ref(`users/${currentUser.uid}/userInfo`)
.on('value', snapshot => {
const userInfo = _.map(snapshot.val(), (val, uid) => {
return { ...val, uid };
});
console.log(userInfo);
dispatch({ type: USERINFO_FETCHED, payload: userInfo });
});

Actions.main();

dispatch({
type: LOGIN_USER_SUCCESS,
payload: user
});
})
.catch(() => {
dispatch({
type: LOGIN_USER_FAIL,
});
});
};
};

这些函数无序运行,因为它们是异步函数。好吧,我们都知道。我想把这些功能整理一下。首先,我想运行并完成此代码:

const { currentUser } = firebase.auth();
firebase.database().ref(`users/${currentUser.uid}/userInfo`)
.on('value', snapshot => {
const userInfo = _.map(snapshot.val(), (val, uid) => {
return { ...val, uid };
});
console.log(userInfo);
dispatch({ type: USERINFO_FETCHED, payload: userInfo });

完成后我想运行这一行:

Actions.main();

这可能吗?我做不到。谢谢您的回答...

最佳答案

简单的修复方法是,在 .on('value' 中尝试类似 Actions.main(); 这样的内容。

export const loginUser = ({ email, password }) => {
return (dispatch) => {
dispatch({ type: LOGIN_USER });

firebase.auth().signInWithEmailAndPassword(email, password)
.then(user => {
const { currentUser } = firebase.auth();
firebase.database().ref(`users/${currentUser.uid}/userInfo`)
.on('value', snapshot => {
const userInfo = _.map(snapshot.val(), (val, uid) => {
return { ...val, uid };
});
console.log(userInfo);
dispatch({ type: USERINFO_FETCHED, payload: userInfo });
Actions.main();
});
dispatch({
type: LOGIN_USER_SUCCESS,
payload: user
});
})
.catch(() => {
dispatch({
type: LOGIN_USER_FAIL,
});
});
};
};

关于javascript - 如何在 React-Native 中按顺序运行异步函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54972975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com