Ale*_*kiy 0 asynchronous event-loop async-await dart
Dart 如何在不阻塞的情况下运行异步代码?例如:
void test(User user) async {
print('test');
String fullName = user.firstName + ' ' + user.lastName;
final result = await sendRequest(fullName);
print('${result}');
}
Run Code Online (Sandbox Code Playgroud)
我知道当 Dart 运行 async 函数时,它会在 await 之前执行代码,然后将剩余的代码包装到 Future 中并将其放入事件循环中。但是,我们正在等待的 Future ( await sendRequest(fullName)
) 如何不阻塞运行另一个同步代码?我们应该等待请求完成,但它也需要一些代码来检查我们是否收到或未收到响应。它如何不阻止其他操作,例如按钮单击?
该函数在第一个返回await
。它返回一个稍后将完成的未来(然后由于void
返回类型而被忽略)。函数中的其他所有内容都会对来自其他期货(或流,如果您使用await for
)的回调做出反应。
async
这里的函数基本上被重写为:
void test(User user) {
print('test');
String fullName = user.firstName + ' ' + user.lastName;
return sendRequest(fullName).then((final result) { // <-- Returns here, synchronously.
print('${result}'); // <-- Gets called by the future of `sendRequst(fullName)`.
});
}
Run Code Online (Sandbox Code Playgroud)
这种转换类似于continuation-passing 样式转换,因为它采用 continuation(在 之后的函数体中的控制流await
)并将其变成一个函数。
(在现实中,转型是比较复杂的,因为它需要考虑到循环,try
/ catch
/ finally
,甚至break
语句。正因为如此,即使是一个简单的例子是这样一个可能会被转换成东西比绝对必要的复杂)。
归档时间: |
|
查看次数: |
43 次 |
最近记录: |