Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
Async/Await Functions - Second Then Runs Before First Then
import React, { useEffect, useState } from "react";
import { View, Text, StyleSheet, Image, FlatList } from "react-native";
import PostComponent from "../../Components/PostComponent";
import { db } from "../../firebase";
import {
  collection,
  query,
  getDocs,
  orderBy,
  doc,
  getDoc,
} from "firebase/firestore";

const postData = [];
const firstData = [];

async function getPosts() {
  const q = query(collection(db, "Posts"), orderBy("postTime"));
  const querySnapshot = await getDocs(q);
  querySnapshot.forEach((postDatas) => {
    const dataPost = postDatas.data();
    firstData.push({ id: postDatas.id, dataPost });
    
  });
}
const getUserDetails = async (a, b) => {
  const docRef = doc(db, "Users", a.creator);
  const docSnap = await getDoc(docRef);

  if (docSnap.exists()) {
    const userDetails = docSnap.data();
    postData.push({ id: b, ...a, ...userDetails });
    console.log("1st: " + postData);
    
  } else {
    
    console.log("No such document!");
  }
};

function Posts() {
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    getPosts()
      .then(() => {
        console.log("Get Posts Complete");
        console.log(firstData.length);
        firstData.forEach((a) => getUserDetails(a.dataPost, a.id));
      })
      .then(() => console.log("2nd " + postData))
      .catch((e) => console.log(e));
  }, []);

  const renderPosts = ({ item }) => <PostComponent />;

  if (loading) {
    getPosts();
    return <Text>Loading Posts</Text>;
  }
  return (
    <View>
      <FlatList data={postData} renderItem={renderPosts} />
    </View>
  );
}

const styles = StyleSheet.create({});

export default Posts;

I refer to the code above.

What I am trying to achieve is to retrieve documents from the User collection based on result from the Post collections. However, I want the console.log("1st: " + postData); in the getUserDetails function to run before the console.log("2nd " + postData). But every time I run the code, the second one runs first before the first. This is a dilemma to me as I thought the first then is supposed to completely run before moving to the second then. Kindly help

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!