MIRROR: javascript for 馃悳's, a tiny runtime with big ambitions
1// Real-world async pattern: sequential operations
2async function fetchUser(id) {
3 console.log(`Fetching user ${id}...`);
4 return new Promise(resolve => setTimeout(() => {
5 resolve({ id, name: `User${id}` });
6 }, 50));
7}
8
9async function fetchUserPosts(userId) {
10 console.log(`Fetching posts for user ${userId}...`);
11 return new Promise(resolve => setTimeout(() => {
12 resolve([`Post1 by ${userId}`, `Post2 by ${userId}`]);
13 }, 30));
14}
15
16async function getUserData(id) {
17 const user = await fetchUser(id);
18 console.log("Got user:", user.name);
19
20 const posts = await fetchUserPosts(user.id);
21 console.log("Got posts:", posts.length);
22
23 return { user, posts };
24}
25
26// This is the common pattern - sequential async calls within one function
27getUserData(123).then(data => {
28 console.log("Complete!", data.user.name, "has", data.posts.length, "posts");
29});