Utilizing the array reduce method in combination with promises

I am working on a function that extracts data from the current path to create an array ([x, y, z, a, b]). This array is then passed into the reduce method to generate a new array of objects. My goal is to pass each value from the initial array into a function that returns an object, and append that object to the new array. However, when I check the results by console.logging 'accumulate', nothing is being printed out. How can I utilize promises to ensure that the results of accumulate are fully displayed?

let accumulate = path.search
      .substring(1)
      .split("+")
      .reduce((acc, val) => {
        FetchMovie(val).then((res) => {
          acc.push(res);
        });
        return acc;
      }, []);

Answer №1

If you want to use promises in a reducer, make sure to resolve all the promises first. One approach is to split the string, create a new Promise, and then wait for all the promises to finish.

Check out this code snippet:

const numbers = [10, 20, 30, 40, 50]; // values after splitting

Promise.all(
  // using map instead of reduce
  numbers.map(num => fetchNumber(num))
).then(
  // display the updated array
  updatedArray => console.log(updatedArray)
)

Answer №2

The function you provide to .then() is executed in an asynchronous manner, causing acc not to be populated until after the completion of your reduce operation (which occurs too late). To address this issue, you can utilize Promise.all() by first utilizing a mapping function (.map()) to convert all your values into Promises returned by your FetchMovie function as follows:

const combinedPromises = Promise.all(path.search
  .substring(1)
  .split(""+"").map(value => FetchMovie(value))
);

combinedPromises
  .then(results => console.log(results))
  .catch(error => console.error(error));

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

The Handlebars template remains blank, failing to show any data or error messages

//////////////////////////////////// // Function to append items // ////////////////////////////////// function addItems(data) { var template = document.getElementById('items').innerHTML; var handlebarsTemplate = Handlebars.compile(tem ...

Pop-up triggered by AJAX XMLHTTPRequest

Essentially, I am attempting to create a fade in/out popup located in the corner of my webpage. For example, when John Doe logs online, I want a notification to appear. This is achieved by using AJAX to check for new updates and displaying the popup if nec ...

What causes Child component to re-render in this basic example of React?

After devouring countless articles on React renders and composition, I found myself in a sea of conflicting information. However, I remember a key point that stood out to me: if React still has the same children prop it received from the App last time, it ...

Steps to completely eliminate all elements from an object using specific keys

I have been pondering the most efficient method to delete all elements of an object through an onClick function. The goal is for the handler to remove all elements. Despite attempts with methods like the delete keyword and filtering, clicking the clear all ...

Encountering difficulties reaching $refs within component method

Trying to access a ref defined within a template when an element is clicked. Here's the HTML: <!DOCTYPE html> <html lang="en"> <head> <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protectio ...

Error ENCOUNTERED when deploying React App to AzureThis is my own fresh

My React website is running on Azure and serving pages successfully. Although, I frequently encounter error messages in the Web App logs like this: 2021-03-01T15:01:33.957751902Z 15:01:33 0|static-page-server-8080 | [2021-03-01T15:01:33.956Z] Error while ...

How to process JSON data that includes a function

I'm trying to replicate a similar diagram using dynamic input data. Here is a basic example of how I'm attempting to achieve this: <script> var myYears = ', 1991, 1992, 1993, 1994, 1995, 1998'; //auto-generated var myValues = ...

React Material UI Select component is failing to recognize scrolling event

Having some difficulty understanding how to detect a scroll event with a Select component using Material-UI. The Select has MenuProps={...}, and I want to listen for the scroll event inside it. I've tried putting onScroll within MenuProps={...}, but ...

Search for images related to a specific keyword using either AngularJS or Node.js, similar to how Google's image

Is there a way to fetch images using AngularJs or Nodejs? For instance, I have implemented a basic search button with HTML, CSS, and AngularJs. Here is an example of using the Simple Angular Http GET Method: $http({ method: 'GET', url: &apo ...

What strategies are available for managing intricate nested data conversions in TypeScript with lodash?

I am currently developing a TypeScript project that involves performing intricate transformations on deeply nested JSON data. While I am utilizing lodash for utility functions, I have encountered a challenge in the following scenario: { "users" ...

Expanding Images with React-Bootstrap Cards

I need assistance with setting up cards in React-Bootstrap. The Card component is enlarging my images beyond their original sizes. When I attempt to place the image in an img tag outside of the card, it displays at its normal size. Can someone provide guid ...

Troubleshooting IE Resolution Problem with getElementsByClassName

I am struggling with how to fix the getElementsByClassName issue in IE. What is the best way to incorporate the Robert Nyman solution into my code without being able to post the link? Or should I consider using a jQuery solution instead? Here's the co ...

Storage Options for Keeping Data Locally: Local Storage and Session

Here is the HTML code snippet I'm working with: <h2>Welcome User!!!</h2> <form class="container" action="/product"> <div> <label for="mail"><b>Email ID: [(ngModel)]</b> ...

What is the best way to connect to the express.js/passport.js API using an Android device as the client

Trying to access an express.js API created with node.js and passport.js. Certain methods only work when the req.user is available. Attempting to log in with Facebook and Twitter from my client app results in a plain cookie being returned. The cookie look ...

What is the best way to continuously call a URL using jQuery until the desired result is obtained?

I have a jQuery script that interacts with a Jenkins web server to initiate a build process. The duration of this build process is unknown, and one way to determine if the build is completed is by checking the JSON API for the status key "building." If thi ...

Using a bytearray for MD5 hashing in Python 2.6: A step-by-step guide

Python versions 2.7 and 3.4 have the capability to perform the following code snippet: import hashlib m = hashlib.md5() m.update(bytearray(128)) However, Python 2.6 will throw an error message: m.update(bytearray(128)) TypeError: update() argumen ...

"Update content dynamically with PHP-AJAX only when there are

Hey there, I've got a comment system that's being constantly updated with jQuery. My goal is to only refresh it when new records are added to the database. Is this possible? Please forgive any mistakes in my English, as I'm using Google Tra ...

Autocomplete for Converting Postal Codes to Cities

I'm currently working on a project that involves two input fields, as shown below: <div class="form-group{{ $errors->has('plz') ? ' has-error' : '' }}"> <label for="plz" class ...

Adding a SpotLight to Camera in ThreeJS: A Step-by-Step Guide

Trying to add a flashlight effect using Three.js r105 I'm attempting to attach a SpotLight to the camera to achieve a "Flashlight" effect. However, once I connect the SpotLight to my Camera, the light seems to completely stop working. What could be t ...

Unresolved promise rejection on Repl.it

I decided to add a basic leaderboard feature to my game on Repl.it, so I set up a node.js backend for it. Here's the code snippet for the backend: const express = require('express'); const Client = require('@replit/database'); cons ...