Typescript: Delivering outcomes in a promising way

How do I convert the function below to return a promise for proper handling in the Page where it is called?

getUploads() {
    const rootDef = this.db.database.ref();
    const uploadsRef = rootDef.child('userUploads').orderByChild('time');
    const userRef = rootDef.child("userProfile");
    var uploads = [];

    uploadsRef.once("value").then((uploadSnaps) => {

      uploadSnaps.forEach((uploadSnap) => {

        var upload = uploadSnap.val();

        userRef.child(uploadSnap.val().user).once("value").then((userSnap) => {
          upload.displayName = userSnap.val().displayName;
          upload.avatar = userSnap.val().avatar;
          uploads.push(upload);
        });

      });

    });

    return uploads;
}

I attempted the code below, but encountered an error. How can I make the necessary modifications?

return new Promise((resolve, reject) => {
  resolve(uploads);
});

To call this method, use the following syntax.

this.db.getUploads().then((uploads) => {
  this.allUploads = uploads;
  console.log(this.allUploads);
});

Answer №1

In order to improve your method, I suggest encapsulating the data within a block of code like this:

fetchData() {
    return new Promise((resolve, reject) => {
        // implementation
        resolve(data); // replace "return data"
    });
}

Answer №2

If you're looking to handle asynchronous operations in JavaScript, consider using the Promise.resolve method:

When you use Promise.resolve(value), it creates a Promise object that will be resolved with the provided value. If the value is thenable (contains a "then" method), the new promise will track its state; otherwise, it will be fulfilled with the original value.

To implement this, you can simply do:

return Promise.resolve(uploads);

The issue in your current code arises from returning the value before the execution of

uploadsRef.once("value").then(...)
. To fix this, make sure to return the result inside the then block like so:

return uploadsRef.once("value").then((uploadSnaps) => {
    ...
    return uploads;
};

Answer №3

This function ensures that all asynchronous calls are handled properly and retrieves all uploads:

fetchUploadsData() {
    const rootRef = this.db.database.ref();
    const uploadsReference = rootRef.child('userUploads').orderByChild('time');
    const userReference = rootRef.child("userProfile");

    return uploadsReference.once("value").then((uploadSnapshots) => {

      return Promise.all(uploadSnapshots.map(uploadSnapshot => {
        var uploadData = uploadSnapshot.val();

        return userReference.child(uploadSnapshot.val().user).once("value").then((userSnapshot) => {
          uploadData.displayName = userSnapshot.val().displayName;
          uploadData.avatar = userSnapshot.val().avatar;
          return uploadData;
        });        
      }));
    });
}

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 a variable by using a conditional operation in JavaScript

When the statement <code>name = name || {} is used, it throws a reference error. However, using var name = name || {} works perfectly fine. Can you explain how variable initialization in JavaScript functions? ...

Combining enums and functions

I have found the concept of combining enums with namespaces to be incredibly valuable. For instance, consider the following: enum Status : { OK = 1, NOT_OK = 2, } namespace Status { function Color(status : Status) { if(status == Sta ...

Looking to spice up your static HTML site? Dive into the world of Ruby on

I recently developed an app that features a static HTML webpage containing text and images, and now I'm interested in incorporating Ruby on Rails to explore its capabilities further. After creating a basic RoR application, I copied the HTML content f ...

How do I prevent a specific word from being removed in a contenteditable div using JavaScript?

Attempting to create a terminal-like experience in JS, I am looking to generate the word 'current source, current location' (e.g., admin@ubuntuTLS~$: ~/Desktop) at the beginning which cannot be removed. Also, I want to prevent the caret from bein ...

"What is the most efficient method to display or hide multiple divs using

Hey, I'm trying to figure out how to work with showing or hiding multiple div elements quickly. Do I really need to number each div like "open,close,show_text"? It seems a bit repetitive if I have to do it for each div 10 times. Open 1 Close 1 hell ...

I'm curious if there is a method to incorporate localStorage into the initialState of Redux Toolkit within Next.js 14

Attempting to establish the initial value of a Redux Toolkit slice for dark mode using localStorage is proving problematic in Next.js, as the window object is not defined on the server-side, resulting in errors. The typical workaround involves using if (t ...

Mastering the flow of control in Node.js programs

Attempting to grasp control flow within Node.js applications. Specifically, does control loop back to the original function once the callback method completes, similar to a callback stack in recursive calls? A simple program was crafted to make a GET call ...

Utilizing AMAZON_COGNITO_USER_POOLS in conjunction with apollo-client: A comprehensive guide

Struggling to populate my jwtToken with the latest @aws-amplify packages, facing some challenges. Encountering an error when attempting to run a Query: Uncaught (in promise) No current user It seems that when using auth type AMAZON_COGNITO_USER_POOLS, I ...

What can you do with a 2D array and getElementsByTagName?

My current challenge involves trying to utilize JavaScript to access table cells by using the getElementsByTagName method. The end goal is to compare each cell in the array to a specific value and then change the background color of that cell based on the ...

Make a POST request using AJAX to the current page and retrieve a value using the $_POST method

I've been trying to solve this puzzle, but I can't seem to figure out what's going wrong... Here's the situation: I'm passing a value to a function and using AJAX to send this value via a POST request to the same page. Upon succes ...

failure to properly assign a property during model update in mongoose

My BaseSchema contains logic that should set values for two properties when a new Model is created: schema.pre("save", function (next) { if (!schema.isNew) { this.createDate = new Date(); this.createBy = "kianoush"; } next(); }); If updating, ...

Congratulations! Your product has been successfully added to Magento using Ajax

While using Firebug, I discovered that JSON generates a message within the success function. However, I am having trouble figuring out how to display it. As a workaround, I attempted to add the following code snippet: if(data.status == 'ERROR'){ ...

Showing dummy data in demo mode with an AngularJS table

I stumbled upon this interesting jsfiddle http://jsfiddle.net/EnY74/20/ that seems to be using some demo data. If you check out this example https://jsfiddle.net/vsfsugkg/2/, you'll notice that the table originally has only one row, but I modified it ...

Ways to implement two functions within a single onclick event

Is it possible to call two functions with onclick event? <input id = "test" onclick="func1()"> Can I add another function as well? How would I go about doing that? ...

Employing async/await for efficient data retrieval

Attempting to utilize async-await in TypeScript Vue 3 to retrieve data, but encountering an issue where the function is already logging 'undefined' (or executing before the function call) private async exportDataOrder() { await this.getDataEx ...

Displaying the contents of a slot in various locations within a web component

The Challenge I am currently utilizing Angular and its Angular Elements to produce Webcomponents. My goal is to allow clients the flexibility to pass custom icons into slots, enabling them to control the appearance of the icons being used. However, this ...

Printing documents from a database using Mongoose version 7.3.1: A comprehensive guide

Currently, with Mongoose 7.3.1, I have inserted some documents into the MongoDB database. However, when I try to log these documents using console.log() by using Fruit.find({}) and outputting it to the console, I get a massive dataset of unwanted objects. ...

In MUI React, the opacity of the placeholder is customizable and can be easily adjusted. This allows for the placeholder to be hidden

Currently, I am facing an issue with a filled variant TextField from Mui React. I have tried to modify it using theme components, but the placeholder text becomes hidden when the field is not focused. See here for Before Focus And here for On Focus I hav ...

Eliminate item from array based on certain criteria

In certain scenarios, I must update the filters. Under specific data conditions, I am required to eliminate 1 item from an array. Here is the code snippet: useEffect(() => { let canceled = false; const filters = [ new C ...

jquery persistently selects element even after altering the class

Having an issue with a button that needs to change its function after meeting a certain condition. I am attempting to select the button by its class, remove that class when the condition is met, add a new class, and then perform another action. However, i ...