Skip to content

Instantly share code, notes, and snippets.

@willie-hung
Last active July 12, 2023 18:47
Show Gist options
  • Save willie-hung/fc5785af80e1ea3bc7dc5a6e26af45b7 to your computer and use it in GitHub Desktop.
Save willie-hung/fc5785af80e1ea3bc7dc5a6e26af45b7 to your computer and use it in GitHub Desktop.
post_6
function fetchUser(userId: number): Promise<string> {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (userId === 1) {
resolve("Sung-Jie Hung");
} else {
reject("User not found");
}
}, 2000);
});
}
function fetchUserPosts(user: string): Promise<string[]> {
return new Promise((resolve) => {
setTimeout(() => {
const posts = ["Post 1", "Post 2", "Post 3"];
resolve(posts);
}, 1500);
});
}
function fetchUserComments(user: string): Promise<string[]> {
return new Promise((resolve) => {
setTimeout(() => {
const comments = ["Comment 1", "Comment 2"];
resolve(comments);
}, 1000);
});
}
Promise.all([
fetchUser(1),
fetchUserPosts("John Doe"),
fetchUserComments("John Doe"),
])
.then(([user, posts, comments]) => {
console.log("User:", user);
console.log("User Posts:", posts);
console.log("User Comments:", comments);
})
.catch((error) => {
console.error("Error:", error);
});
// Output:
// User: Sung-Jie Hung
// User Posts: [ 'Post 1', 'Post 2', 'Post 3' ]
// User Comments: [ 'Comment 1', 'Comment 2' ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment