[英]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? 如何使下面的函数返回一个Promise,以便可以在调用此函数的Page中正确处理它?
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 : 您可以使用Promise.resolve :
The Promise.resolve(value) method returns a Promise object that is resolved with the given value.
Promise.resolve(value)方法返回使用给定值解析的Promise对象。 If the value is a thenable (ie has a "then" method), the returned promise will "follow" that thenable, adopting its eventual state;
如果该值是一个thenable(即具有“ then”方法),则返回的Promise将“跟随”该thenable,并采用其最终状态; 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. 但是代码的问题是,在
uploadsRef.once("value").then(...)
之前返回该值。
You should simply return the result from then
: 您应该简单地
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;
});
}));
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.