<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Uchenna Emeruche</title>
    <description>The latest articles on DEV Community by Uchenna Emeruche (@uchennaemeruche).</description>
    <link>https://dev.to/uchennaemeruche</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F446537%2F1eae1874-140f-48f7-9de5-9145aa222a56.jpeg</url>
      <title>DEV Community: Uchenna Emeruche</title>
      <link>https://dev.to/uchennaemeruche</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/uchennaemeruche"/>
    <language>en</language>
    <item>
      <title>Iterating asynchronous operations in dart(using forEach and for..in loop)</title>
      <dc:creator>Uchenna Emeruche</dc:creator>
      <pubDate>Tue, 15 Dec 2020 13:17:03 +0000</pubDate>
      <link>https://dev.to/uchennaemeruche/iterating-asynchronous-operations-in-dart-using-foreach-and-for-in-loop-1n4f</link>
      <guid>https://dev.to/uchennaemeruche/iterating-asynchronous-operations-in-dart-using-foreach-and-for-in-loop-1n4f</guid>
      <description>&lt;p&gt;Most hight-level programming languages ships with iteration statements, dart is not an exception.&lt;br&gt;
For one to handle highly scalable and efficient business logic using dart, a detailed knowledge of asynchronous operations, futures, loops among others is a can’t-do-without.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In this article, We’ll focus specifically on the &lt;code&gt;for..in&lt;/code&gt; and &lt;code&gt;forEach&lt;/code&gt; loops as used in asynchronous operations.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Generally, both the &lt;code&gt;for-in&lt;/code&gt; and &lt;code&gt;forEach&lt;/code&gt; constructs are used to loop over iterables(List, Set, etc). Both have a return type of void. .i.e(a new value can not be returned from these methods), neither do they expose the current index of the iteration unlike the typical &lt;code&gt;for..loop&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Enough of the general notes, let’s see how these constructs handle asynchronous operations in dart.&lt;/p&gt;

&lt;p&gt;Take a closer look at the examples below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;List&amp;lt;Person&amp;gt; persons = [
  Person(
    name: "Emeruche U.K",  
    images:["ImageProfile", "My Image2"],
  ),
];


class Person{
   String name;
   List&amp;lt;String&amp;gt; images;

   Person({this.name, this.images});
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void main() {
  Future uploadImages({images, name})async{
    return ["Image 1", "image 2"];
  }

  Future updateProfile(Person person) async{
    List&amp;lt;String&amp;gt; newImageUrls = [];
    person.images.forEach((image) async{
       if (image.runtimeType == String) {
        dynamic url = await uploadImages(images: [image], name: person.name);
        print("forEach URL: $url");
        newImageUrls.addAll(url);
      } else {
        newImageUrls.add(image);
      }
    });
    print("Profile Images f1: $newImageUrls");

    person..images = newImageUrls;
  }

  updateProfile(persons[0]);

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From the above snippet, using the &lt;strong&gt;&lt;code&gt;for..Each&lt;/code&gt;&lt;/strong&gt; construct might seem like a natural choice when looping over a list using async/await. Typically, we expect the synchronous-reading magic of &lt;code&gt;async/await&lt;/code&gt; to do what it says and actually &lt;code&gt;await&lt;/code&gt; the promise. Often times this gives an unexpected output or even throw a &lt;strong&gt;&lt;code&gt;ReferenceError&lt;/code&gt;&lt;/strong&gt; if the result of the operation is being used somewhere else in the application (as seen in above code).&lt;/p&gt;

&lt;p&gt;To fix this, we can either switch to the &lt;code&gt;for..in&lt;/code&gt; construct or use the &lt;code&gt;Future.forEach&lt;/code&gt; method. This should do the trick&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; Future updateProfile2(Person person) async {
    List&amp;lt;String&amp;gt; newImageUrls = [];
    for (var image in person.images) {
      if (image.runtimeType == String) {
        dynamic url = await uploadImages(images: [image], name: person.name);
        print("for..in URL: $url");
        newImageUrls.addAll(url);
      } else {
        newImageUrls.add(image);
      }
    }
    print("Profile Images f2: ${newImageUrls}");

    person..images = newImageUrls;
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First, we changed the for..Each block to a for..in construct…why? Switching to a for..in block solved the problem because the &lt;code&gt;for..each&lt;/code&gt; returns the &lt;code&gt;empty result set&lt;/code&gt; first before processing the await function inside the forEach. It just applies the function on each element and calls next without awaiting for the asynchronous operation to return. But the for..in construct on the other hand, actually awaits the result of the execution of the function before calling next&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Future updateProfile3(Person person) async {
    List&amp;lt;String&amp;gt; newImageUrls = [];

    await Future.forEach(person.images, (image)async{
       if (image.runtimeType == String) {
        dynamic url = await uploadImages(images: [image], name: person.name);
        print("Future.forEach URL: $url");
        newImageUrls.addAll(url);
      } else {
        newImageUrls.add(image);
      }
    });

    print("Profile Images f3: $newImageUrls");

    person..images = newImageUrls;
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The  &lt;code&gt;Future.forEach()&lt;/code&gt; waits for each Future to be completed before moving to the next element.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;When you need to wait for multiple Futures to complete irrespective of their order, you can use Future.wait() method like this:&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Future.wait(person.images.map(functionCall));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Future.wait([futureOne(), futureTwo(), …]).then((res) =&amp;gt; functionToCallAfterResult(res));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Error handling in asynchronous code&lt;/strong&gt;&lt;br&gt;
Errors from your asynchronous code can be handled using the &lt;code&gt;try..catch&lt;/code&gt; block in dart. Essentially, if an error is thrown within the try block, such can be received and handled with the catch block.&lt;/p&gt;

</description>
      <category>dart</category>
      <category>programming</category>
      <category>mobile</category>
      <category>flutter</category>
    </item>
  </channel>
</rss>
