将结果作为Typescript中的承诺返回

时间:2017-05-29 13:56:55

标签: javascript typescript promise

如何使下面的函数返回一个promise,以便我可以在调用此函数的Page中正确处理它?<​​/ p>

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

我尝试了下面的内容,但它显示错误。我该如何修改?

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

我将调用此方法,如下所示。

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

3 个答案:

答案 0 :(得分:2)

我认为您可以使用

包围方法的内容
getUploads() {
    return new Promise((resolve, reject) => {
        // content of method
        resolve(uploads); // instead of "return uploads"
    });
}

答案 1 :(得分:1)

您可以使用Promise.resolve

  

Promise.resolve(value)方法返回一个Promise对象   用给定的值解决。如果该值是可以的(即具有a   &#34;然后&#34;方法),返回的承诺将&#34;跟随&#34;那个,   采用其最终状态;否则返回的承诺将是   实现了价值。

如此简单:

return Promise.resolve(uploads);

但是代码的问题在于,在调用uploadsRef.once("value").then(...)之前返回值 您应该只返回then

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

答案 2 :(得分:0)

这应该正确处理异步调用并返回所有上传:

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