Struggling with the task of populating an array inside a promise

I'm in the process of creating a social networking site where users can connect with each other. I am facing an issue in one of my routes where I need to extract posts from the following array of current users, sort them by date, and send them as a single array to the client side. However, the problem is that the posts are not being added to the array before it gets sent to the client. I'm unsure if I should use an async function or some other method.

This is the route for fetching posts:

const express = require('express')
const user = require("../models/user")
const router = express.Router()

router.get("/api/:username/following/posts", (req, res) => {
    let following = [...req.user.following, req.user._id]
    let posts = [], i;
    for(i = 0; i < following.length; i++){
        User.findById(following[i]).populate("posts")
            .then(user => {
                for(let b = 0; b < user.posts.length; b++){
                    posts.push(user.posts[b])
                }
            })
            .catch(err => {
                console.log(err)
            })
    }
    console.log(posts) // returns []
    res.json(posts) 
})

Answer №1

Using async/await

router.get("/api/:username/following/posts", async (req, res) => {
    const following = [...req.user.following, req.user._id]
    const posts = [];
    for(let f of following){
        const user = await User.findById(f).populate("posts");
        posts.push(...user.posts);
    }
    console.log(posts)
    res.json(posts) 
})

using Promises only

router.get("/api/:username/following/posts", (req, res) => {
    const following = [...req.user.following, req.user._id];
    Promise.all(following.map(f => User.findBy(f).populate("posts")))
    .then(users => {
        const posts = users.map(({posts}) => posts).flat();
        console.log(posts);
        res.json(posts);
    });
})

The main contrast lies in how the code handles asynchronous operations. In the Promises-only version, calls to User.findBy are made concurrently while in the async/await version they are executed sequentially. However, both versions maintain the order of operations.

If you face issues with parallel calls but prefer not to use async/await, you can approach it like this:

router.get("/api/:username/following/posts", (req, res) => {
    const following = [...req.user.following, req.user._id];
    Promise.all(
        following.reduce((p, f) => p.then(results => User.findBy(f).populate("posts").then(user => [...results, user])), Promise.resolve([])
    )
    .then(users => {
        const posts = users.map(({posts}) => posts).flat();
        console.log(posts);
        res.json(posts);
    });
})

Answer №2

Implementing async/await is one option, while another approach would be to place the res.json call within the .then method.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: DataTables FixedColumn module "Uncaught ReferenceError: FixedColumns is not defined"

I am currently struggling to implement the FixedColumns plugin from datatables. I am following the example code provided on the website: $(document).ready( function () { var oTable = $('#example').dataTable( { "sScrollX": "100%", ...

The jQuery dropdown selection for only displaying the month and year is not functioning properly when using the select

Currently, I am utilizing a datepicker with only the month and year as options to select from using dropdowns. However, when I apply the following CSS to disable the days of the datepicker, it ends up affecting all datepickers in my JSP file. 1. Is there ...

Why was the 'Symbol' type introduced in ECMA-262-v6 and what purpose does it serve?

Can you explain the purpose of the 'Symbol' type in ECMA-262-v6? Is it used for fast path implementation for object keys? How does it work internally - does it hash with the assurance that the underlying data remains unchanged? ...

Isotope animation glitches causing malfunction

I've been experimenting with CSS3 transitions on isotope items, but I'm encountering some strange behavior. My goal is to achieve a fading effect on the items, similar to this example: . Thank you in advance! Here's what I have so far: http ...

Double invocation of AngularJS custom filter

I have successfully created a custom filter using AngularJS that displays only the fruits that begin with the letter "p." Although I believe my custom filter is implemented correctly, I have noticed that it is being called twice. While searching for simil ...

Integrating data between Java and JavaScript within the Wikitude platform is essential for leveraging AR.RelativeLocation

After passing an integer from Java to JavaScript, I am attempting to use the value to adjust the altitude of an object. I included the variable in RelativeLocation var location = new AR.RelativeLocation(null, 8, 0, a); The issue arises when it disregards ...

In the context of Nuxt 3 / Vue, reversing an array within a v-for loop can lead to certain properties being wrongly linked to specific

In my simple component, I have a list of articles with properties such as name, number, link, and publishedDate displayed in order: <script setup> const props = defineProps({ items: { type: Object, required: true }, }) </sc ...

What is the process for configuring SSL certificates for a web server's CNAME using NodeJS and ExpressJS?

After successfully configuring SSL certificates for a NodeJS web server in the setup outlined below, everything is running smoothly: process.env.HTTPS_PORT = 3000; // Listening on HTTPS port 3000. process.env.HTTP_PORT = 6000; // Listening on HTTP ...

The functionality of the code in a stack snippet may differ from that in a standalone HTML file

My code works perfectly on a stack snippet, but when I insert it into my server or an .html file, the refresh button shrinks! I have copied and pasted the code exactly as it is. Are there any specific snippet features that need to be added for it to work, ...

Encounter an error parsing the package.json file. Confirmed that it is valid JSON

As I embark on creating my very first yeoman generator, I have encountered an issue when running yo to initiate the project. The error message I am receiving is as follows: npm ERR! install Couldn't read dependencies npm ERR! Darwin 14.0.0 npm ERR! a ...

Choose only one option from the dropdown menu at a time within the specified div

I attempted to utilize the "setSelected" option on my multiselect feature, but I noticed that it does not function with div elements (at least I could not make it work myself). I am endeavoring to create two synchronized multiselects using this example: b ...

Turning a string retrieved from the element's data attribute into a JSON format

I am running into an issue with the code snippet below. It seems that $.parseJSON() is having trouble with single and double quotes. I'm stuck on finding a solution to this problem. Any help would be greatly appreciated! <div data-x='{"a":"1" ...

Activate the jQuery function multiple times

I am currently working on the menu structure for my website <div class="header"> <ul> <li id="menu__lnk_one"><a href="#">Home</a></li> <li><a href="#">Our Story</a></ ...

Tips for building a custom error handling function specifically designed for parsing and handling errors in

Is there a way to reduce redundancy in my code, such as: let name = ""; try { name = data[" "][0][" "][0][" "][0][" "][1][" "][0][" "][1]["C"]; } catch (error) { if (error instanceof TypeError) { console.log("name TypeError"); } } I have consid ...

Obtaining the designated item within the list

My list contains elements obtained from a database. I want to ensure that the selected elements remain visible at all times, even after refreshing the page. Here's an example: <select id="select-firm" class="form-control" name="firmId" size="20" ...

Trouble with Prestashop 1.6.1.16 JS Product Functionality

When I try to switch between sizes, the price does not change and I am encountering errors in the console from product.js. I am currently using Prestashop 1.6.1.16. Error: Uncaught ReferenceError: productPrice is not defined at updateDisplay (product ...

Retrieving the value of a submit button within the `onSubmit` event handler in a React application

In my usual process, I typically handle the form submission by utilizing the onSubmit handler. <form onSubmit={e => { ... } }> <input ... /> <input ... /> <button type="submit">Save</button> </form> ...

Enable users to establish a timetable for executing server-side scripts in NodeJS

In my current Node & Express project, I am looking to implement a functionality where users can schedule the server to run test scripts periodically, like every ten minutes. After exploring options such as node-schedule, I discovered that all scheduled tas ...

Retrieving Information from an API with Custom Headers in React Native

I have an API that necessitates specific headers for access. Without these headers, a browser displays the following error: Code: 4101 Message: Header X-Candy-Platform is required However, when the headers are provided, the API returns a json response. ...

The middleware code remains dormant and is left untouched

I am encountering an issue with this code that is supposed to create a folder if it doesn't already exist. When I debug and set a breakpoint on fs.mkdir, the code does not enter into it. Do you have any idea what could be causing this problem? ... ap ...