简体   繁体   English

等待必须与 JavaScript 中的异步方法一起使用

[英]Is await mandatory to use with async method in JavaScript

I was discussing with someone else about the use of async/await in JavaScript and we didn't agree.我在JavaScript和别人讨论async/await的使用,没同意。

Personally, I only use await when I need to wait for the async method to be finished.就个人而言,我只在需要等待异步方法完成时才使用 await 。 If I don't need it to finish to continue, I don't.如果我不需要它完成继续,我就不需要。 Eg:例如:

async myAsyncMethod() {
    axios.get(`/foo`)
    .then((response) => {
        this.foo = response.data;
     }).catch (exception) {
        //do something with exception
        this.foo = null;
    };
}

If I need the data right away, I call:如果我马上需要数据,我会打电话:

await myAsyncMethod();

If I don't, I do:如果我不这样做,我会:

myAsyncMethod();

Is it not correct to do this last one?这样做最后一个不正确吗? The other person maintained that I should not.另一个人坚持认为我不应该。 If so, would it be possible to explain to me why.如果是这样,是否可以向我解释为什么。


I've edited the myAsyncMethod() to be more precise.我编辑了 myAsyncMethod() 以使其更精确。 So my questions implies that that I catch errors and that I know that 'foo' is either null either field with data at some point... The point is that I don't need those data right away and I've got other things to do that don't require it.所以我的问题意味着我发现了错误并且我知道'foo'是null或者在某个时候有数据的字段......关键是我不需要这些数据马上而且我还有其他东西这样做不需要它。

An async function without an await expression will run synchronously.没有await表达式的async function 将同步运行。

The await expression causes async function execution to pause until a Promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment. await表达式导致async function 执行暂停,直到 Promise 已解决(即完成或拒绝),并在完成后恢复执行异步 function。

So, in your case, the myAsyncMethod will return an unsettled promise unless you await it.因此,在您的情况下,除非您等待,否则myAsyncMethod将返回未解决的 promise。

References:参考:

  1. Async function 异步 function
  2. Await operator 等待接线员

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM