Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to chain asynchronous tasks?

I have a list of urls that I have to check sequentially. When one of the content retrieved at the url matches a given criteria I have to stop otherwise the next url has to be tested.

The problem is that retrieving content for a given url is an asynchronous task so I can't use a simple for-each loop.

What is the best way to do that ?

For now my code looks like that :

List<String> urls = [/*...*/];
void f() {
  if (urls.isEmpty) return; // no more url available
  final url = urls.removeAt(0);
  getContent(url).then((content) {
    if (!matchCriteria(content)) f(); // try with next url
    else doSomethingIfMatch();
  });
}
f();
like image 207
Alexandre Ardhuin Avatar asked May 26 '26 22:05

Alexandre Ardhuin


1 Answers

The Quiver package contains several functions to iterate with async.

doWhileAsync, reduceAsync and forEachAsync perform async computations on the elements of on Iterables, waiting for the computation to complete before processing the next element.

doWhileAsync seems to be exactly what is wanted :

List<String> urls = [/*...*/];
doWhileAsync(urls, (url) => getContent(url).then((content) {
  if (!matchCriteria(content)) {
    return new Future.value(true); // try with next url
  } else {
    doSomethingIfMatch();
    return new Future.value(false);
  }
}));
like image 99
Alexandre Ardhuin Avatar answered May 30 '26 10:05

Alexandre Ardhuin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!