[英]How to return a promise inside the async await in javascript?
Is it ok to do something like this?做这样的事情可以吗?
I mean, Is return await new Promise()
a valid expression as of below?:我的意思是,
return await new Promise()
是如下的有效表达式吗?:
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()
函数的一个例子是:
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.这使您上面的代码完全有效,除非您不需要在返回中包含
await
。
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}
更改
{...image, url}
以return {...image, url}
Additional response:补充回复:
To retrieve the contents of a promise, use the .then() method.要检索承诺的内容,请使用 .then() 方法。 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.如果这回答了您的问题,请将其标记为已接受的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.