简体   繁体   中英

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);
});

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"
    });
}

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 (ie 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
};

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;
        });        
      }));
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM