088_async5.zig 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. //
  2. // Sure, we can solve our async value problem with a global
  3. // variable. But this hardly seems like an ideal solution.
  4. //
  5. // So how do we REALLY get return values from async functions?
  6. //
  7. // The 'await' keyword waits for an async function to complete
  8. // and then captures its return value.
  9. //
  10. // fn foo() u32 {
  11. // return 5;
  12. // }
  13. //
  14. // var foo_frame = async foo(); // invoke and get frame
  15. // var value = await foo_frame; // await result using frame
  16. //
  17. // The above example is just a silly way to call foo() and get 5
  18. // back. But if foo() did something more interesting such as wait
  19. // for a network response to get that 5, our code would pause
  20. // until the value was ready.
  21. //
  22. // As you can see, async/await basically splits a function call
  23. // into two parts:
  24. //
  25. // 1. Invoke the function ('async')
  26. // 2. Getting the return value ('await')
  27. //
  28. // Also notice that a 'suspend' keyword does NOT need to exist in
  29. // a function to be called in an async context.
  30. //
  31. // Please use 'await' to get the string returned by
  32. // getPageTitle().
  33. //
  34. const print = @import("std").debug.print;
  35. pub fn main() void {
  36. var myframe = async getPageTitle("http://example.com");
  37. var value = ???
  38. print("{s}\n", .{value});
  39. }
  40. fn getPageTitle(url: []const u8) []const u8 {
  41. // Please PRETEND this is actually making a network request.
  42. return "Example Title.";
  43. }