如果我希望一切都按顺序在函数内执行,是否等待每一行? [英] If I want everything to execute, in order, inside a function, do I await each line?

查看:78
本文介绍了如果我希望一切都按顺序在函数内执行,是否等待每一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我肯定我的大脑在异步/等待过程中并不完全清楚,所以我需要澄清一下。我看到了很多示例,其中在某些行上使用了await,而在标记为async的函数中未使用其他代码。例如,我很少见过这样的示例(我使用print语句作为简单/基本示例):

I know for sure my brain isn't totally clear on async/await so I need some clarity. I see a lot of examples where await is used on some lines and not others inside a function marked async. For example, I rarely if ever have seen an example like this (I am using the print statement as an example of something simple/basic.):

myFunction() async {
  await functionA();
  await print("This really long thing that's going to print out.");
  await functionB();
  await MyExtraClass.lookupSomethingQuickly();
  ...
}

所以我看到的示例通常类似于

So the examples I see it's usually something like this:

myFunction() async {
  await functionA();
  print("This really long thing that's going to print out.");
  await functionB();
  MyExtraClass.lookupSomethingQuickly();
  ...
}

所以我想知道是否只是一个假设简单的事情会按顺序完成,或者如果从理论上讲,在每行的前面放个等待是万一我绝对需要第1行跟随第2行跟随第3行的情况下应该做的事情,等等。

So I am wondering if there's just an assumption that simple things will complete in order or if theoretically, putting await in front of each line is what I should be doing in cases where I absolutely need line 1 to follow line 2 to follow line 3, etc... Like what if I absolutely need that print to finish before functionB() goes off?

从本质上来说,每次我用async / await编写函数时,我发现自己在每行上都进行判断调用,并且我永远不知道我的代码是否由于良好的时机和运气而工作,或者是否有可能导致执行中断的案例。

Essentially I find myself making a judgment call on every line every time I am writing a function with async/await and I never know if my code is working because of good timing and luck or if there would ever be cases that would throw the execution off.

推荐答案

async / await 是为了使异步代码更易于编写,阅读和推理。同步代码不需要这种支持。

有关Dart中的异步编程,另请参见 https://www.dartlang.org/docs/tutorials/futures/

async / await is to make asynchronuos code easier to write, to read and to reason about. Synchronuos code doesn't need such support.
For async programming in Dart see also https://www.dartlang.org/docs/tutorials/futures/

如果您使用此代码示例

import 'dart:async' show Future;
void main() {
  doSomethingAsync().then((_) => print('afterwards'));
  print('at last');
}

Future doSomethingAsync() {
  return new Future.delayed(const Duration(seconds: 1), () {
    print('done something');
  });
}

DartPad

可打印


最后

之后做了一些事情

at last
done something
afterwards

如果不熟悉异步执行,这可能令人惊讶

If you're not familiar with async execution this might be surprising

这是因为执行了传递给 Future.delayed()的代码延迟1秒。当 Future.delayed中的代码延迟时,由 doSomethingAsync()返回的 Future 实例完成。 ()已执行。

This is because code passed to Future.delayed() is executed with a delay of 1 second. The Future instance returned by doSomethingAsync() "completes" when the code in Future.delayed() has been executed.

在此行

doSomethingAsync().then((_) => print('afterwards'));

我们称。然后(...) doSomethingAsync()返回的 Future 上,并将闭包(内联函数)传递给 .then(...)。 ((_)=> print('afterwards'))。

we call .then(...) on the Future returned by doSomethingAsync() and pass a closure (inline function) to .then(...). ((_) => print('afterwards')).

<$ c $的特征c>未来是它在完成后调用传递给 then(...)的代码(在我们的例子中为完成某件事在延迟1秒后打印出来。)

A feature of Future is that it calls the code passed to then(...) after it was completed (in our case when done something was printed after 1 sec delay).

所以执行过程类似于


  • 调用 doSomethingAsync()将调用计划为 print('done something)供以后执行,并返回 Future

  • 调用 print('atlast'); 最后只打印

  • 1秒钟延迟后 print('done something ')称为

  • doSomethingAsync()返回的未来 已完成

  • 未来调用`(_)=> print('afterwards')

  • main()结尾。

  • call doSomethingAsync() which schedules a call to print('done something) for later execution and returns a Future
  • call print('at last'); which just prints at last
  • after 1 second delay print('done something') is called
  • the Future returned from doSomethingAsync() is completed
  • the Future calls `(_) => print('afterwards')
  • main() ends.

当我们使用 async / await 代码类似于

When we use async / await the code looks like

import 'dart:async' show Future;
Future main() async {
  await doSomethingAsync();
  print('afterwards');
  print('at last');
}

Future doSomethingAsync() {
  return new Future.delayed(const Duration(seconds: 1), () {
    print('done something');
  });
}

DartPad

运行时,输出为


完成某些操作
之后再做


最后

done something
afterwards
at last

我们还可以在 doSomethingAsync()中使用 async / await 但是现在我们只关注 main()

we also could use async / await in doSomethingAsync() but now we only focus on main()

现在执行看起来像


  • 调用 doSomething()并等待返回的 Future 完成

  • print('done something')被执行, Future 已完成

  • 等待之后继续执行代码

  • print('afterwards');

  • print('atlast');

  • call doSomething() and wait for the returned Future to complete
  • print('done something') is executed and the Future completed
  • the execution of code after await continues
  • print('afterwards');
  • print('at last');

这可能是您预期的行为。

This is probably the behavior you expected.

对于您的原始问题。 等待仅在调用返回将来并且您希望仅在未来已完成。如果调用未返回 Future ,则没有任何等待。

To your original question. await is only necessary when a call returns a Future and you want the following code only be executed when the Future was completed. If the call doesn't return a Future there is nothing to wait for.

await print('xxx')仍然是有效代码。这是为了支持有时执行一些异步工作并返回 Future 的功能,但有时没有异步工作来立即执行代码并随后返回。在这种情况下,没有什么可等待的。

await print('xxx') is still valid code. This is to support functions that sometimes do some async work and return a Future but sometimes the don't have async work to do and execute the code immediately and just return afterwards. In this case there is nothing to wait for.

someTimesAsync() {
  if(new DateTime.now().weekday == 1) {
    return new Future.delayed(const Duration(seconds: 1), () {
      print('done something');
    });
  } else {
    print('done something');
  }
}





await someTimesAsync();

在两种情况下均有效。如果不是这样,那将很麻烦。

works in both cases. If it wouldn't this would be cumbersome.

有关 async / await 的详细信息 https://www.dartlang.org/articles/await-async/

For more details about async / await see also https://www.dartlang.org/articles/await-async/

这篇关于如果我希望一切都按顺序在函数内执行,是否等待每一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆