dart - Sum of integer values of a Future -
i'm trying parse html document, image-sources , add size of pictures together. parsing document works fine, getting image-sources , getting size.
main(){ print("please input url"); var url = stdin.readlinesync(); getimageurls(url).then((list) { list.foreach((imageurl) { getimagesize(imageurl).then((r) { print("$imageurl, size: $r bytes"); }); }); }); } future<int> getimagesize(string url){ final completer = new completer(); new streamcontroller()..stream.listen((str) => completer.complete(imagesize(str)))..add(url); return completer.future; } imagesize(string url){ return http.get(url).then((response) => response.bodybytes.length); }
i'm struggeling add size of each individual image 1 integer. figured this
main(){ int total = 0; print("please input url"); var url = stdin.readlinesync(); getimageurls(url).then((list) { list.foreach((imageurl) { getimagesize(imageurl).then((r) { print("$imageurl, size: $r bytes"); total += r; }); }); }); print(total); }
but i'd need wait getimageurls finish before im able print total.
can push me in right direction? feel i'm missing obvious.
the easiest way use "new" async
/await
main() async { int total = 0; print("please input url"); var url = stdin.readlinesync(); var list = await getimageurls('url'); for(int = 0; < list.length; i++) { var imageurl = list[i]; var r = await getimagesize(imageurl); print("$imageurl, size: $r bytes"); total += r; } print(total); }
or future.wait
mentioned in comment
main(){ int total = 0; print("please input url"); var url = stdin.readlinesync(); getimageurls(url).then((list) { return future.wait(list.map((r) { return getimagesize(imageurl).then((r) { print("$imageurl, size: $r bytes"); total += r; }); }); }).then((_) => print(total)); }
Comments
Post a Comment