Asynchronous 如何链接异步任务?
我有一个我必须按顺序检查的URL列表。当url中检索到的内容之一符合给定条件时,我必须停止,否则必须测试下一个url 问题是检索给定url的内容是一项异步任务,因此我不能使用简单的for each循环 最好的方法是什么 目前,我的代码如下所示:Asynchronous 如何链接异步任务?,asynchronous,dart,Asynchronous,Dart,我有一个我必须按顺序检查的URL列表。当url中检索到的内容之一符合给定条件时,我必须停止,否则必须测试下一个url 问题是检索给定url的内容是一项异步任务,因此我不能使用简单的for each循环 最好的方法是什么 目前,我的代码如下所示: 列出URL=[/*…*/]; void f(){ if(url.isEmpty)return;//没有更多可用的url 最终url=url.removeAt(0); 获取内容(url)。然后((内容){ 如果(!matchCriteria(content
列出URL=[/*…*/];
void f(){
if(url.isEmpty)return;//没有更多可用的url
最终url=url.removeAt(0);
获取内容(url)。然后((内容){
如果(!matchCriteria(content))f();//尝试下一个url
else doSomethingIfMatch();
});
}
f();
我的一个想法是将整个操作的结果分离到另一个未来的中,并对其作出反应。这将传输找到的、有效的URL内容或可对其作出反应的错误。异步getContent
操作的完成要么以一个结果、一个错误满足未来,要么重试。
请注意,在此(以及您的)方法中,url
列表在操作运行时不得被任何其他方法修改。如果在每个序列的开始处创建新的列表(如示例所示),则一切正常
List<String> urls = [/*...*/];
Completer<String> completer = new Completer<String>();
void f() {
if (urls.isEmpty) completer.completeError(new Exception("not found"));
final url = urls.removeAt(0);
getContent(url).then((content) {
if (!matchCriteria(content)) f(); // try with next url
else completer.complete(content);
}).catchError((error) { completer.completeError(error); });
}
completer.future.then((content) {
// url was found and content retrieved
}).catchError((error) {
// an error occured or no url satisfied the criteria
});
列出URL=[/*…*/];
Completer Completer=新的Completer();
void f(){
if(url.isEmpty)completer.completeError(新异常(“未找到”);
最终url=url.removeAt(0);
获取内容(url)。然后((内容){
如果(!matchCriteria(content))f();//尝试下一个url
完成(内容);
}).catchError((错误){completer.completeError(错误);});
}
completer.future.then((内容){
//找到url并检索内容
}).catchError((错误){
//发生错误或没有满足条件的url
});
包含几个用于异步迭代的函数
doWhileAsync
、reduceEASYNC
和forEachAsync
对on-Iterables的元素执行异步计算,等待计算完成后再处理下一个元素
似乎正是我们想要的:
列出URL=[/*…*/];
doWhileAsync(url,(url)=>getContent(url)。然后((内容){
如果(!匹配条件(内容)){
返回新的Future.value(true);//尝试下一个url
}否则{
doSomethingIfMatch();
返回新的Future.value(false);
}
}));