admin 管理员组文章数量: 1086019
an example:
async doSomething() {
await asyncCall();
}
Do I need to use await
when I call my doSomething
function?
await doSomething();
or is this fine?
doSomething();
an example:
async doSomething() {
await asyncCall();
}
Do I need to use await
when I call my doSomething
function?
await doSomething();
or is this fine?
doSomething();
Share
Improve this question
asked Jun 4, 2021 at 20:34
avokevdoavokevdo
1195 bronze badges
5
-
1
Do you want to wait for
doSomething()
to finish or not? Do you want to handle any errors it might throw? – VLAZ Commented Jun 4, 2021 at 20:35 -
@VLAZ Yes, I do want to wait for
doSomething()
to finish – avokevdo Commented Jun 4, 2021 at 20:36 -
then you need
await
. if you want to run it in the background and not wait you dont useawait
. – Lux Commented Jun 4, 2021 at 20:36 -
2
Then...you have to
await
it. That's whatawait
does. – VLAZ Commented Jun 4, 2021 at 20:36 -
An
async function
always returns a promise, regardless whether you useawait
in the body or not, and yes you will need toawait
(orreturn
) that promise. – Bergi Commented Jun 4, 2021 at 21:09
2 Answers
Reset to default 7It's important to understand that async/await is really just "sugar" on top of Promises. In other words, doSomething
still returns a Promise
(you can't use async await to get away from this fact!). So, to answer your question, you still need to use await
(or chain a then
call) to handle the eventual resolved or rejected Promise value.
In your example, doSomething()
returns a Promise. For you to return the data from an async function, you need to resolve or reject the promise.
When you do:
await doSomething();
doSomething()
will wait for asyncCall()
to be resolved.
When you do:
doSomething();
doSomething()
will resolve asyncCall()
in the background.
I think your confusion es from the fact that await is only valid in async functions in javascript. If you want to run await doSomething()
outside a async function, just wrap it around an anonymous async function like:
(async() => {
await doSomething()
})();
本文标签:
版权声明:本文标题:javascript - If I define an async function and use await in the body, do I need to use await when calling the function? - Stack 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1744063212a2527107.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论