我确信我的大脑在async / await上并不完全清楚所以我需要一些清晰度。我看到很多例子在某些行上使用了await而在标记为异步的函数中没有使用其他行。例如,我很少见过像这样的例子(我使用print语句作为简单/基本的例子。):
myFunction() async {
await functionA();
await print("This really long thing that's going to print out.");
await functionB();
await MyExtraClass.lookupSomethingQuickly();
...
}
所以我看到的例子通常是这样的:
myFunction() async {
await functionA();
print("This really long thing that's going to print out.");
await functionB();
MyExtraClass.lookupSomethingQuickly();
...
}
所以我想知道是否只是假设简单的事情会按顺序完成,或者理论上,等待在每一行的前面是我应该做的事情,我绝对需要第1行跟随第2行跟随第3行等等...如果我在functionB()关闭之前绝对需要完成打印?
基本上我发现自己每次使用async / await写一个函数时都会在每一行上进行判断调用,而且我不知道我的代码是否正常工作,因为时机和运气都很好,或者是否会出现抛出的情况执行关闭。
答案 0 :(得分:5)
async
/ await
是使asynchronuos代码更容易编写,阅读和推理。同步代码不需要这样的支持
对于Dart中的异步编程,另请参阅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');
});
}
中试用
打印
最后
做了一些事 之后
如果您不熟悉异步执行,这可能会令人惊讶
这是因为传递给Future.delayed()
的代码以1秒的延迟执行。当Future
中的代码已执行时,doSomethingAsync()
返回的Future.delayed()
实例“完成”。
在这一行
doSomethingAsync().then((_) => print('afterwards'));
我们在.then(...)
返回的Future
上调用doSomethingAsync()
,并将闭包(内联函数)传递给.then(...)
。 ((_) => print('afterwards')
)。
Future
的一项功能是,它会在完成后调用传递给then(...)
的代码(在我们的情况下,在延迟1秒后打印done something
时)。
所以执行类似于
doSomethingAsync()
调度print('done something)
以便稍后执行并返回Future
print('at last');
,只打印at last
print('done something')
被称为Future
返回的doSomethingAsync()
已完成Future
调用`(_)=> print('afterwards')main()
结束。 当我们使用async
/ await
时,代码看起来像
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');
});
}
中试用
运行时,输出为
做了一些事情 事后
最后
我们也可以在async
中使用await
/ doSomethingAsync()
,但现在我们只关注main()
现在执行看起来像
doSomething()
并等待返回的Future
完成print('done something')
已执行且Future
已完成await
继续print('afterwards');
print('at last');
这可能是您期望的行为。
原来的问题。 await
仅在调用返回Future
时才需要,并且您希望仅在Future
完成时执行以下代码。如果呼叫没有返回Future
,则无需等待。
await print('xxx')
仍然是有效的代码。这是为了支持有时会执行某些异步工作并返回Future
的函数,但有时候没有异步工作要做,并立即执行代码,然后再返回。在这种情况下,没有什么可以等待的。
someTimesAsync() {
if(new DateTime.now().weekday == 1) {
return new Future.delayed(const Duration(seconds: 1), () {
print('done something');
});
} else {
print('done something');
}
}
await someTimesAsync();
适用于这两种情况。如果不这样做会很麻烦。
有关async
/ await
的详细信息,另请参阅https://www.dartlang.org/articles/await-async/