问题描述
我正在尝试创建 Web 服务器流.代码如下:
I am trying to create a web server stream. Here is the code:
import 'dart:io';
main() async {
HttpServer requestServer = await HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 8000);
requestServer.listen((request) { //comment out this or the await for to work
request.response
..write("This is a listen stream")
..close();
});
await for (HttpRequest request in requestServer) {
request.response
..write("This is an await for stream")
..close();
}
}
listen 和 await for 有什么区别?它们不能同时工作.您需要注释掉其中一个才能工作,但这里的功能似乎没有区别.在某些情况下是否存在差异,您应该何时使用一种而不是另一种?
What is the difference between listen and await for? They both do not work at the same time. You need to comment out one or the other to work, but there doesn't seem to be a difference in function here. Are there circumstances where there is a difference, and when should you use one over the other?
推荐答案
鉴于:
Stream<String> stream = new Stream<String>.fromIterable(['mene', 'mene', 'tekel', 'parsin']);
然后:
print('BEFORE');
stream.listen((s) { print(s); });
print('AFTER');
产量:
BEFORE
AFTER
mene
mene
tekel
parsin
鉴于:
print('BEFORE');
await for(String s in stream) { print(s); }
print('AFTER');
产量:
BEFORE
mene
mene
tekel
parsin
AFTER
stream.listen()
设置代码,当事件到达时将其放入事件队列,然后执行以下代码.
stream.listen()
sets up code that will be put on the event queue when an event arrives, then following code is executed.
await for
在事件之间挂起并继续这样做直到流完成,所以在它发生之前不会执行跟随它的代码.
await for
suspends between events and keeps doing so until the stream is done, so code following it will not be executed until that happens.
我使用 `await for 当我有一个我知道将有有限事件的流时,我需要在做任何其他事情之前处理它们(基本上就像我在处理一个期货列表一样).
I use `await for when I have a stream that I know will have finite events, and I need to process them before doing anything else (essentially as if I'm dealing with a list of futures).
检查 https://www.dartlang.org/articles/language/beyond-async 对 await for
的描述.
Check https://www.dartlang.org/articles/language/beyond-async for a description of await for
.
这篇关于Dart 中等待和聆听的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!