Dart 飞镖流,相当于等待
我喜欢Dart中的Dart 飞镖流,相当于等待,dart,async-await,Dart,Async Await,我喜欢Dart中的等待构造 如何使用常规for循环实现类似的功能 差不多 // beware! fictional code. var element = stream.next(); for(; stream.isEndReached(); element = stream.next()) { // use element here } // or probably it will be like this, right? var element = await stream.next
等待构造
如何使用常规for循环实现类似的功能
差不多
// beware! fictional code.
var element = stream.next();
for(; stream.isEndReached(); element = stream.next()) {
// use element here
}
// or probably it will be like this, right?
var element = await stream.next();
for(; await stream.isEndReached(); element = await stream.next()) {
// use element here
}
但是我不知道应该使用什么函数来代替这里的next()
和isEndReached()
。如果您能给我一个与
异步操作完全相同的完整示例,那就太好了
编辑:以下是我要求这样做的实际原因:我想做这样的事情:
if (!stream.isEndReached()) {
var a = await stream.next();
// use a
}
if (!stream.isEndReached()) {
var b = await stream.next();
// use b
}
// have an arbitrary number of these
我需要像这样一件一件地消费物品。这就是为什么我要问我的.next()
和.isEndReached()
方法映射到流类中的实际方法 包中包含一个类,该类可以执行您想要的操作
另请参阅这篇伟大的文章
StreamQueue
为流提供了一个基于拉的API
从上面提到的文章中截取的代码
void main() async {
var queue = new StreamQueue(new Stream.fromIterable([1, 2, 3]));
var first = queue.next;
var second = queue.next;
var third = queue.next;
print(await Future.wait([first, second, third])); // => [1, 2, 3]
}
更新
WebStorm(使用dartanalyzer的一项功能)在尚未从该软件包中导入任何内容时,不会为导入提供快速修复。如果在源代码中没有引用包,它就不会读取包。正如我在回答中提到的,StreamQueue
来自async
包<代码>导入“包:async/async.dart”代码>通常就足够了(将包的主入口点文件(async.dart
)命名为与包相同是一种惯例),并且所有导出的标识符在库中都可用。否则,您可以搜索项目的源代码,WebStorm还将搜索依赖项并显示哪个库包含StreamQueue
类。然后可以导入此文件。请参见,使用带有.forEach的闭包是唯一的选项吗?我所说的是不可能的,对吗?您需要使用then()
链接调用,以确保一个调用在另一个调用之后执行。我看不到一个for
循环可以做到这一点。即使如此,我们不能等待的方法是什么?而不是我的下一个()和Isendreched(),我不知道你最后的评论是什么意思。您可以等待这些方法。只是for
并不能提供一种方法来延迟执行,直到上一次迭代中的未来的
完成。当您可以使用wait for()
时,讨论的重点是什么?要使用StreamQueue,我必须找到此代码并粘贴import“package:async/async.dart”show StreamQueue代码>从那里到我的导入。我正在使用WebStorm和ctrl+space,StreamQueue没有自动导入StreamQueue。有没有更简单的方法可以开始使用StreamQueue?