Serdar Gun
Serdar Gun

Reputation: 97

How can I run my asyncronous functions in order in React-Native?

I have an action like this:

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

These functions run unordered because these are asyncronous functions. Alright we all know that. I want to put in order these functions. First of all I want to run and finish this codes:

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

and after finish them I want to run this line:

Actions.main();

Is that possible? I couldn't do it. Thank you for your answers...

Upvotes: 0

Views: 44

Answers (2)

Subhendu Kundu
Subhendu Kundu

Reputation: 3856

Easy fix would be, trying something like Actions.main(); this inside the .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,
        });
      });
  };
};

Upvotes: 1

Omar
Omar

Reputation: 463

You need to learn how to use promises. Below is a good tutorial on serial execution of promises. Enclose your methods in promises and run them Promise.all.

https://decembersoft.com/posts/promises-in-serial-with-array-reduce/

Upvotes: 1

Related Questions