089_async6.zig 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. //
  2. // The power and purpose of async/await becomes more apparent
  3. // when we do multiple things concurrently. Foo and Bar do not
  4. // depend on each other and can happen at the same time, but End
  5. // requires that they both be finished.
  6. //
  7. // +---------+
  8. // | Start |
  9. // +---------+
  10. // / \
  11. // / \
  12. // +---------+ +---------+
  13. // | Foo | | Bar |
  14. // +---------+ +---------+
  15. // \ /
  16. // \ /
  17. // +---------+
  18. // | End |
  19. // +---------+
  20. //
  21. // We can express this in Zig like so:
  22. //
  23. // fn foo() u32 { ... }
  24. // fn bar() u32 { ... }
  25. //
  26. // // Start
  27. //
  28. // var foo_frame = async foo();
  29. // var bar_frame = async bar();
  30. //
  31. // var foo_value = await foo_frame;
  32. // var bar_value = await bar_frame;
  33. //
  34. // // End
  35. //
  36. // Please await TWO page titles!
  37. //
  38. const print = @import("std").debug.print;
  39. pub fn main() void {
  40. var com_frame = async getPageTitle("http://example.com");
  41. var org_frame = async getPageTitle("http://example.org");
  42. var com_title = com_frame;
  43. var org_title = org_frame;
  44. print(".com: {s}, .org: {s}.\n", .{com_title, org_title});
  45. }
  46. fn getPageTitle(url: []const u8) []const u8 {
  47. // Please PRETEND this is actually making a network request.
  48. return "Example Title";
  49. }