Retrieve data within an object.map() function, returning after the mapping process has been completed

I am currently working with a cardsList object that is retrieved from a fetch() function. As I iterate over the cardsList and make additional requests to get more information for each card, I have encountered a peculiar issue. Despite the mapping process being synchronous, the console output shows 'Log2' before 'Log1'.

Strangely, although I can view all the information of the cardInfo objects when I print cardsList, attempting to access it with syntax like cardsList[0].cardInfo returns undefined.

Have you encountered a similar problem before? Any insights into what might be causing this behavior?

*Note: I have experimented with using await in fetchCardsInfo, but the issue persists. I can see the data when I log it, but accessing it seems to be problematic.

buscarCartoes = async () => {
    let cardsList = await CodeConnectRequests.fetchCardsList()

    cardsList.map((card) => {
        const cardInfo = CodeConnectRequests.fetchCardsInfo(card.cartao.tkCartao)
        cardInfo.then(data=>{
            console.log('Log1')
            card['cardInfo'] = data                   
        })

        return card
    })

    console.log('Log2')
    console.log(cardsList)// Here I can see cardInfo infs
    console.log(cardsList[0].cardInfo)// But hete cardInfo will be undefined
}

Answer №1

Promise.all can be a game-changer

retrieveCards = async () => {
    let cardsList = await CodeConnectRequests.fetchCardsList()

    // ensuring all nested requests are completed
    await Promise.all(cardsList.map(async (card) => { // Remember that the callback is async
        card.cardInfo = await CodeConnectRequests.fetchCardsInfo(card.cartao.tkCartao)
        return card
    })

    console.log('Log2')
    console.log(cardsList)// Viewing cardInfo details here
    console.log(cardsList[0].cardInfo)// However, cardInfo will be undefined here
}

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

Separate the iframe sessions

I am working with 6 iframes from the same domain but with different URLs and subdirectories. Each iframe sets a cookie with the same name but a different value using the HTML header "set-cookie". To prevent interference between these cookies, I need to fin ...

Are you receiving a response code 500 when making a request to a presigned URL?

I've been encountering an issue with generating presigned URLs for files from my S3 bucket. Although I can successfully read files and obtain a list of file contents, when attempting to create a presigned URL using the following code snippet: reports ...

Transforming jQuery Object into a String after making an AJAX request

If I were to submit a form with some text in the value of user_input, let's say "I am free," through AJAX, and it comes back to me as a string. Once it becomes an Object, how could I convert it back into a string format? Thanks, <!DOCTYPE HTML> ...

Json node tabbing

[ { "idn" : "liquido", "categoria": "Aromatizante Ambiental Liquido", "productos": [ { "nombre": "Canela" }, { "nombre": "Chanel" }, { "nombre": "Citrus" }, ...

Saving the current $index from an ng-repeat loop to a database row (with row numbers 1.1, 1.2, 1.3) using AngularJS

Currently, I am developing the index page functionality for a book. i.e : 1.1 1.1.1 1.2 1.2.1 In this setup, 1.1 and 1.2 are the parent ng-repeats, while 1.1.1 and 1.2.1 are the child ng-repeats. My goal is to store these numbers ( ...

After updating the INNERHTML, the NAV tag content is no longer functional

I am facing an issue with replacing the contents of a NAV tag that contains UL list items. The original HTML within the NAV tag works perfectly fine, but when I replace it with my own HTML - which matches the original word for word - the dropdown functiona ...

Identify the index of a list item using a custom list created from buttons

When dealing with a dynamically built list like this: <ul id="shortcuts"> <li><input type="checkbox" value="false"/><button>foo</button><button>-</button></li> <li><input type="checkbox" value ...

Is Socket.io exclusive to browsers?

Similar Question: Using socket.io standalone without node.js How to run socket.io (client side only) on apache server My website is hosted on a Linux server with shared hosting. Since I don't have the ability to install node.js, I am looking ...

What is the best way to send a JSON object in Vue.js?

<template> <div id="app"> <div id="bee-plugin-container"></div> </div> </template> <script> // import axios from "axios"; // import Bee from "@mailupinc/bee-plugin"; import $ from 'jquery' ...

Utilizing SEO and incorporating special characters like !# in a website's URL

I came across an interesting concept about designing a website that utilizes AJAX to load each page section without compromising SEO. It involved incorporating !# in the URL, similar to the approach adopted by Twitter. However, I've been unable to loc ...

Issues with audio and video playback intermittently occurring on Sencha Touch 2

As a beginner with Sencha Touch 2, I am currently working on uploading images onto an iPad using Xcode. My app has audio playing on the home screen, and I want the video to start playing and the audio to stop when a specific tab is selected. However, the ...

The persistent issue of window.history.pushstate repeatedly pushing the identical value

I need some assistance with my Vue application. I am trying to update the URL when a user clicks on an element: const updateURL = (id: string) => { window.history.pushState({}, '', `email/${id}`); }; The issue I'm facing is th ...

Exploring the process of retrieving parameters within a component using React Router DOM version 4

I am struggling with the following code: <BrowserRouter> <Route path="/(:filter)?" component={App} /> </BrowserRouter> In previous versions of React Router, wasn't the filter param or '' on the root supposed to be in ...

I am looking to retrieve data from the Graph API JSON and gradually refine my search to achieve successful

I am looking to retrieve data from the "fb_page_categories" endpoint, which provides an array of categories a page can be categorized under. The format for this request is as follows: GET graph.facebook.com /fb_page_categories? Once this request is mad ...

Transform PDF files into PNG format directly in your web browser

I am currently utilizing Vue.js and attempting to convert a PDF file to PNG or another image format directly within the browser. My current setup involves reading the PDF from a URL using PDF.js along with the Vue.js component pdfvuer. let instance = this ...

Using Node.js setTimeout method

I'm struggling with understanding how to utilize the setTimeOut function in NodeJS. Let's say I need: function A() to be executed every 10 seconds. If function A returns 'true' from its callback, it should trigger a call to a specific ...

Prevent users from progressing to the next step without completing the form by implementing a feature in React

To ensure a seamless user experience, I am looking to implement a feature that disables the next button until all form fields are completed. The entire component is provided below for reference. The form utilizes the useFrom() function in react-hook-form ...

retrieving serialized object from an ajax request sent to the web server

As a newcomer to web development, I decided to create an ASP.NET project with a web API to test my skills. In the process, I crafted a controller and some JavaScript files as follows: Controller: namespace MyNamespace.Controllers { public c ...

What is the process for creating a symbolic link from a project's node_modules directory?

Recently, I've been learning how to build a Password Manager using React, Node.js, and MYSQL by following a tutorial. However, I encountered an issue where the file /EncryptionHandler was located outside of the src/ directory of my project. Even thoug ...

Encountering infinite loop in Node modules triggering a Catch-22 situation while attempting to use M

I have been working on a project that involves using some customized Node.js modules. I have developed a 'helpers' module that helps with loading various helper methods: /helpers/index.js: var mutability = require('./mutability'), ...