如何等待异步订阅完全填充全局变量?
How to wait for async subscribe to full fill a global variable?
我有一个类似于以下内容的异步 firebase 调用:
this.fbProvider.fbGetProfile()
.subscribe(p => {
this.profile = p;
});
...但是我需要在其他功能中使用 this.profile
...
console.log(this.profile.email);
...它会ps 返回一个错误:
Cannot read property 'email' of undefined
知道如何在需要使用之前等待订阅完全填充我的局部变量吗?
ps:我的问题比这更大,使用 .then()
等解决方案会使我的代码变得一团糟。我用 await
尝试了一些东西,但效果不佳。
`
您可以使用 async
/ await
承诺并在 api 调用完成后解决:
await new Promise(resolve => {
this.fbProvider.fbGetProfile()
.subscribe(p => {
this.profile = p;
resolve();
});
});
记得在使用此代码的函数前加上 async
。
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 存储的文件的状态变化。使用上述答案中给出的 "await",对我有用!
我有一个类似于以下内容的异步 firebase 调用:
this.fbProvider.fbGetProfile()
.subscribe(p => {
this.profile = p;
});
...但是我需要在其他功能中使用 this.profile
...
console.log(this.profile.email);
...它会ps 返回一个错误:
Cannot read property 'email' of undefined
知道如何在需要使用之前等待订阅完全填充我的局部变量吗?
ps:我的问题比这更大,使用 .then()
等解决方案会使我的代码变得一团糟。我用 await
尝试了一些东西,但效果不佳。
`
您可以使用 async
/ await
承诺并在 api 调用完成后解决:
await new Promise(resolve => {
this.fbProvider.fbGetProfile()
.subscribe(p => {
this.profile = p;
resolve();
});
});
记得在使用此代码的函数前加上 async
。
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 存储的文件的状态变化。使用上述答案中给出的 "await",对我有用!