Steps for ensuring a promise is fulfilled in Node.js and Firebase

I've been struggling with this issue for quite some time now and can't seem to figure it out.

g_globalList.once("value").then(function(tickList){
    var multiPaths = [];    
    tickList.forEach(function(ticker){
        ticker.val().forEach(function(path){
            multiPaths.push(path);
        });
    });
    return multiPaths;        
}).then(function(multiPaths){
    var myObj = {};
    multiPaths.forEach(function(path){
        var ticker = path.substr(path.lastIndexOf("/")+1, 40);
        console.log("adding " + ticker);

        ****this is another promise and make my "myObj" to print blank****

        db.child("symbols/NSE/" +ticker).once('value').then(function(data){
            if(data.exists()){
                myObj[path] = data.val();
            }       
        });
    });
    return myObj;
}).then(function(myObj){
    console.log(myObj);
});

Is there any way that I can delay the final "console.log(myObj)" until after all promises have been completed?

Answer ā„–1

Utilizing Promise#all allows you to wait for all Promises to resolve. Take a look at the code snippet below for an example (not tested, but it might give you some insight on how to tackle your issue):

var allPaths = [];

g_globalList.once("value").then(function(tickList){  
    return Promise.all(
   //map will create a array of the returned values (Promises in this case)
        tickList.map(function(ticker){
            return ticker.val();
        })
    );
}).then(function(values){//values represents all then results
    allPaths = values; //store all paths for later use
    return Promise.all(
        //map will create a array of returned values (Promises in this case)
        values.map(function(path){

            var ticker = path.substr(path.lastIndexOf("/")+1, 40);
            return db.child("symbols/NSE/" +ticker).once('value');
        })
    );
}).then(function(values){//values represents all then results
    var myObj = {}; //let's create an object

    for(var i = 0; i < allPaths.length; i++){ //for each path
        var path = allPaths[i];
        //extract the ticker name again
        var ticker = path.substr(path.lastIndexOf("/")+1, 40);

        //check your data
        var data = values[i];
        if(data.exists()){
            //add to the object
            myObj[path] = data.val();
        }      
    }
    //return the object
    return myObj;
})
.then(function(myObj){
    //hopefully, the object is ready here
    console.log(myObj);
});

Answer ā„–2

Optimize your code by substituting forEach with map on multiPaths. Make sure to capture each db.child call's return value and nest the map function within a Promise.all() for better efficiency.

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

Creating an Observable Collection in Angular using AngularFire2 Firestore

I am currently using material 2 and attempting to develop data tables with pagination and sorting. In order to achieve this, I require my collections to be observable. However, I believe that I might be incorrectly populating or initializing the arrays in ...

When a block is clicked, jQuery will reveal that block while hiding the others sequentially, starting with the second block, then the third, and finally the fourth

Creating a navigation menu with 4 blocks can be a bit tricky, especially when trying to show one block at a time upon click. Here is my code attempt, but unfortunately it's not working as expected. I would greatly appreciate any help or suggestions on ...

Creating a Countdown in Javascript Using a Variable

I want the date to change from the first date to the second date. At the start, it should display 'Starts:' in bold followed by the remaining time. Once it switches to the second date, it should show 'Ends:' in bold and then the remaini ...

Inconsistent reliability of Loopback-context prompts the search for an alternative solution

After encountering some reliability issues with the loopback-context package, I decided to try an alternative approach. Instead of relying on setting the current user object in my middleware using loopback-context, I opted to fetch the accessToken from the ...

I am attempting to assign a default value to a TextField by retrieving data from a GetMapping call in React, however, the value is not being successfully set

I am facing an issue with setting a default value for a TextField in my code. Even though I am trying to populate it with data from a GetMapping call, the value is not being set as expected. Here is the JSON response I receive from the API call: { "id": 1 ...

What causes an error in Express when using res.send() to send an array item containing a number, but not when sending a string?

Query: When using Express, why does an error occur when the res.send() method is used to send a single number from an array, but not when sending a complete array or a string? Illustration 1: In this scenario, everything goes smoothly. Upon requesting the ...

Encountering the error 'Cannot read property 'length' of undefined' while attempting to fetch data from a URL using node.js

While attempting to create a Discord-Bot capable of looking up definitions on urbandictionary, I encountered an error after trying to fetch the json from their api. const args = Array.prototype.slice.call(commandArgs); if (!args.length) { return m ...

What could be causing my page width to only expand to 100% when using "fit-content"?

After searching extensively, I'm unable to find a solution that fits my current issue. My goal is to construct a practice ecommerce website using React. One of the components I have is a header which I'd like to occupy 100% of the screen width, c ...

Is it possible for Vue data to be handled asynchronosly

Have you ever wondered? Is it possible for Vue's data function to be asynchronous? Imagine needing to fetch data from an API using a library like axios, which only offers async methods. How can this data be loaded into Vue's data function? Con ...

Having Trouble Loading Vue Devtools in Vue Electron Builder

I'm encountering an issue with loading Vue Devtools in my Electron application integrated with Vue. This is my first time working with this combination, and I suspect there might be a dependency problem causing the Devtools not to load within the Elec ...

Passport sessions do not retain persistence

Having some trouble implementing OAuth 2.0 login where the sessions don't persist after authentication is a common issue. Additionally, there seems to be a problem with the app getting stuck in the routes/bnetauth.js file during the redirect in the ca ...

Advantages of utilizing bracket notation (alongside variables) for retrieving a property from an object

When it comes to accessing stored information, utilizing alternatives like the dot operator can be straightforward. However, Iā€™m struggling to grasp the significance of using variables in achieving the same goal. For instance: var myObj = { prop1: "v ...

Exploring the Process of Passing Data with MongoDB's find().count()

Currently, I am working on developing a straightforward Express application with MongoDB. I have set up an endpoint that searches for a user by their name and then displays the relevant data stored in the database on the page. While attempting to incorpora ...

Tips for determining the zoom factor through mouse scrolling using jQuery

Is there a way to zoom in on a page when the user scrolls using ctrl + ,? If I determine the Zoom factor, can I then zoom in on the current page based on that factor? For example, if the zoom factor is 1.44, can I convert this to 144% and carry out the ...

When setting up columns in a MUI DataGrid, it's important to remember that each field must have a unique name to avoid any conflicts. Having

I am currently working on a DataGrid project where I aim to display the values of ready_by and name. Here is an image for reference: https://i.stack.imgur.com/3qZGa.png In my code configuration, the setup looks like this: (specifically focusing on the la ...

Effortless method to handle package.json configurations

Is there a better approach for seamlessly transitioning between using npm link and git, or another solution that caters well to both front end and back end developers? The dilemma I'm facing revolves around developing a website that utilizes multiple ...

I'm seeing a message in the console that says "Form submission canceled because the form is not connected." Any idea why this is happening?

For the life of me, I can't figure out why this code refuses to run the handleSubmit function. Essentially, the form is supposed to take an input and execute the handleSubmit function upon submission. This function then makes a POST request to an API ...

A client built using node.js that is equipped with TLS 1.2 compatibility

I need assistance in creating an HTTPS Client that supports TLS 1.2 instead of the default TLS 1.0. Can someone provide guidance on how to enable this feature in my code? var https = require('https'); var util = require('util'); var fs ...

The WebSocket has already transitioned to the CLOSING or CLOSED state in Socket io

Encountering an error with Socket.io: WebSocket is already in CLOSING or CLOSED state in Socket.io. When using Node.js: socket.to(socketId).emit('details', { userdetails: username }); In React JS: socket.on('details', data => { ...

Tips for sending two values to a PHP file using JavaScript Ajax

I have created a code for two dropdown menus. The goal is to select values from both menus and send them to a php file using the GET method. The values should be sent to the php file only when both menus have selections made. Below is the code snippet: ...