Browse Source

Add ex089 Async 6

Dave Gauer 4 years ago
parent
commit
e47dccf245
4 changed files with 63 additions and 4 deletions
  1. 0 4
      TEMP_TODO
  2. 4 0
      build.zig
  3. 53 0
      exercises/089_async6.zig
  4. 6 0
      patches/patches/089_async6.patch

+ 0 - 4
TEMP_TODO

@@ -1,4 +0,0 @@
-071 - inline for - loop through struct fields
-072 - inline while (see lib/std/fmt.zig)
-073 - comptime block
-074 - quiz 8 - revisit 058_quiz7 and make those connections programatically?

+ 4 - 0
build.zig

@@ -434,6 +434,10 @@ const exercises = [_]Exercise{
         .main_file = "088_async5.zig",
         .output = "Example Title.",
     },
+    .{
+        .main_file = "089_async6.zig",
+        .output = ".com: Example Title, .org: Example Title.",
+    },
 };
 
 /// Check the zig version to make sure it can compile the examples properly.

+ 53 - 0
exercises/089_async6.zig

@@ -0,0 +1,53 @@
+//
+// The power and purpose of async/await becomes more apparent
+// when we do multiple things concurrently. Foo and Bar do not
+// depend on each other and can happen at the same time, but End
+// requires that they both be finished.
+//
+//               +---------+
+//               |  Start  |
+//               +---------+
+//                  /    \
+//                 /      \
+//        +---------+    +---------+
+//        |   Foo   |    |   Bar   |
+//        +---------+    +---------+
+//                 \      /
+//                  \    /
+//               +---------+
+//               |   End   |
+//               +---------+
+//
+// We can express this in Zig like so:
+//
+//     fn foo() u32 { ... }
+//     fn bar() u32 { ... }
+//
+//     // Start
+//
+//     var foo_frame = async foo();
+//     var bar_frame = async bar();
+//
+//     var foo_value = await foo_frame;
+//     var bar_value = await bar_frame;
+//
+//     // End
+//
+// Please await TWO page titles!
+//
+const print = @import("std").debug.print;
+
+pub fn main() void {
+    var com_frame = async getPageTitle("http://example.com");
+    var org_frame = async getPageTitle("http://example.org");
+
+    var com_title = com_frame;
+    var org_title = org_frame;
+
+    print(".com: {s}, .org: {s}.\n", .{com_title, org_title});
+}
+
+fn getPageTitle(url: []const u8) []const u8 {
+    // Please PRETEND this is actually making a network request.
+    return "Example Title";
+}

+ 6 - 0
patches/patches/089_async6.patch

@@ -0,0 +1,6 @@
+44,45c44,45
+<     var com_title = com_frame;
+<     var org_title = org_frame;
+---
+>     var com_title = await com_frame;
+>     var org_title = await org_frame;