Is it ok to do something like this?
I mean, Is return await new Promise()
a valid expression as of below?:
async pushImage(image, basePath) {
const imgId = this.angularDatabase.createPushId();
const route = `${basePath}${imgId}`;
const imageRef = this.angularFireStorage.ref(route);
return await concat(
imageRef.put(image.image).snapshotChanges().pipe(ignoreElements()),
defer(() => imageRef.getDownloadURL())
)
.pipe(
map(
(url) => (
{ ...image, url }
)
)
)
.toPromise();
}
Anything returned from an async functions comes out as a promise.
For example:
async getDate() {
return new Date();
}
will return a promise with the contents of a date.
An example of reading this overly complicated getDate()
function would be:
getDate().then(date => {
console.log("The date: ", date);
});
However, you can also return a promise. This makes your code above perfectly valid, except you don't need to include the await
in the return.
You can "simply" just say
return concat(
imageRef.put(image.image).snapshotChanges().pipe(ignoreElements()),
defer(() => imageRef.getDownloadURL())
).pipe(
map(url => {
return {...image, url}
})
).toPromise();
Side note: I am not certain, but I think you should return the object in the map. Changing {...image, url}
to return {...image, url}
Additional response:
To retrieve the contents of a promise, use the .then() method. Example:
myReturnedPromise.then(dataOfMyReturnedPromise => {
//This code is called after the promise is resolved.
console.log("The returned value is: ", dataOfMyReturnedPromise);
}).catch(error => {
//If this code is called, the promise completed with an error
//This might be executed if you're retreiving data from the internet
//and your internet connection is too poor to get the data
console.error("Error: ", error);
});
If this answered your question, please mark it as the accepted answer.
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.