Purus
Purus

Reputation: 5819

Returning results as a promise in Typescript

How can I make the below function to return a promise so that I can handle it properly in the Page that calls this function?

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 tried the below, but it shows error. How should I modify?

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

I will be calling this method as shown below.

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

Upvotes: 0

Views: 1560

Answers (3)

Steffen Schmitz
Steffen Schmitz

Reputation: 890

This should handle the asynchronous calls correctly and return all uploads:

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

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

      return Promise.all(uploadSnaps.map(uploadSnap => {
        var upload = uploadSnap.val();

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

Upvotes: 0

Nitzan Tomer
Nitzan Tomer

Reputation: 164417

You can use Promise.resolve:

The Promise.resolve(value) method returns a Promise object that is resolved with the given value. If the value is a thenable (i.e. has a "then" method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value.

So simply:

return Promise.resolve(uploads);

But the problem with your code is that you return the value before the uploadsRef.once("value").then(...) has been invoked.
You should simply return the result from then:

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

Upvotes: 1

user3050534
user3050534

Reputation: 237

I think you could surround the contents of your method with

getUploads() {
    return new Promise((resolve, reject) => {
        // content of method
        resolve(uploads); // instead of "return uploads"
    });
}

Upvotes: 3

Related Questions