diff options
author | Dave Gauer <dave@ratfactor.com> | 2021-05-13 19:48:10 -0400 |
---|---|---|
committer | Dave Gauer <dave@ratfactor.com> | 2021-05-13 19:48:10 -0400 |
commit | 00f525c80f8a7785852092af246b28fe8fac1893 (patch) | |
tree | 9b9607e3cf7607aaa1ee8f0ab5a7364199c93492 | |
parent | 469d4dfbf40dd5512f53ce1cb022e1aa4639443b (diff) | |
download | ziglings-00f525c80f8a7785852092af246b28fe8fac1893.tar.gz ziglings-00f525c80f8a7785852092af246b28fe8fac1893.tar.bz2 ziglings-00f525c80f8a7785852092af246b28fe8fac1893.tar.xz ziglings-00f525c80f8a7785852092af246b28fe8fac1893.zip |
add ex088 async 5 await
-rw-r--r-- | build.zig | 4 | ||||
-rw-r--r-- | exercises/088_async5.zig | 47 | ||||
-rw-r--r-- | patches/patches/088_async5.patch | 4 |
3 files changed, 55 insertions, 0 deletions
@@ -430,6 +430,10 @@ const exercises = [_]Exercise{ .main_file = "087_async4.zig", .output = "1 2 3 4 5", }, + .{ + .main_file = "088_async5.zig", + .output = "Example Title.", + }, }; /// Check the zig version to make sure it can compile the examples properly. diff --git a/exercises/088_async5.zig b/exercises/088_async5.zig new file mode 100644 index 0000000..523fa73 --- /dev/null +++ b/exercises/088_async5.zig @@ -0,0 +1,47 @@ +// +// Sure, we can solve our async value problem with a global +// variable. But this hardly seems like an ideal solution. +// +// So how do we REALLY get return values from async functions? +// +// The 'await' keyword waits for an async function to complete +// and then captures its return value. +// +// fn foo() u32 { +// return 5; +// } +// +// var foo_frame = async foo(); // invoke and get frame +// var value = await foo_frame; // await result using frame +// +// The above example is just a silly way to call foo() and get 5 +// back. But if foo() did something more interesting such as wait +// for a network response to get that 5, our code would pause +// until the value was ready. +// +// As you can see, async/await basically splits a function call +// into two parts: +// +// 1. Invoke the function ('async') +// 2. Getting the return value ('await') +// +// Also notice that a 'suspend' keyword does NOT need to exist in +// a function to be called in an async context. +// +// Please use 'await' to get the string returned by +// getPageTitle(). +// +const print = @import("std").debug.print; + +pub fn main() void { + var myframe = async getPageTitle("http://example.com"); + + var value = ??? + + print("{s}\n", .{value}); +} + +fn getPageTitle(url: []const u8) []const u8 { + // Please PRETEND this is actually making a network request. + return "Example Title."; +} diff --git a/patches/patches/088_async5.patch b/patches/patches/088_async5.patch new file mode 100644 index 0000000..7ce4fc6 --- /dev/null +++ b/patches/patches/088_async5.patch @@ -0,0 +1,4 @@ +39c39 +< var value = ??? +--- +> var value = await myframe; |