[英]How can I run my asyncronous functions in order in React-Native?
我有這樣的動作:
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();
那可能嗎? 我做不到。 謝謝您的回答...
您需要學習如何使用諾言。 下面是關於promise的串行執行的一個很好的教程。 將您的方法包含在promise中並運行它們Promise.all。
https://decembersoft.com/posts/promises-in-serial-with-array-reduce/
容易解決的辦法是,嘗試使用類似Actions.main();
這在.on('value'
。
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,
});
});
};
};
如果您希望在獲得userInfo
的值后運行Actions.main()
, userInfo
可以將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,
});
});
};
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.