如何等待异步订阅以完全填充全局变量?

时间:2017-09-03 20:18:29

标签: angular firebase asynchronous angularfire

我有一个类似于:

的异步firebase调用
this.fbProvider.fbGetProfile()
               .subscribe(p => {                                       
                            this.profile = p;
                         });

...但是我需要在其他函数中使用this.profile,如...

console.log(this.profile.email);

...并且它不断返回错误:

  

无法阅读财产'电子邮件'未定义的

在我需要使用之前,我怎么能等待订阅完全填充我的局部变量?

ps:我的问题比这更大,而使用.then()等解决方案使我的代码变得混乱。我用await尝试了一些东西,但它也没有用。

`

2 个答案:

答案 0 :(得分:0)

您可以使用async / await承诺并在api呼叫完成后解决此问题:

await new Promise(resolve => {
    this.fbProvider.fbGetProfile()
           .subscribe(p => {                                       
                        this.profile = p;
                        resolve();
                     });
});

请记住将async放在使用此代码的函数之前。

答案 1 :(得分:0)

  async uploadToStorage(element) {
    var imgUrl = "";
    var uploadTask = this.gallery_ref.child('Gallery/' + element.name).put(element);
    // Listen for state changes, errors, and completion of the upload.

    await new Promise(resolve => {

      uploadTask.on('state_changed', snapshot => {
        // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
        var progress = (uploadTask.snapshot.bytesTransferred / uploadTask.snapshot.totalBytes) * 100;
        console.log('Upload is ' + progress + '% done');
        }
      }, error => {

      }, function () {
        // Upload completed successfully, now we can get the download URL
        uploadTask.snapshot.ref.getDownloadURL().then(function (downloadURL) {
          imgUrl = downloadURL;
          console.log("url");
          console.log(imgUrl);
          resolve();
        });
      });
    })
    return imgUrl
  }

这是一个Firebase函数,用于跟踪上传到Firebase存储的文件的状态更改。使用以上答案中给出的“等待”对我有用!

相关问题