Skip to content

Instantly share code, notes, and snippets.

@datlife
Last active May 19, 2019 01:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save datlife/50d89c046f5508ba1fbbe9ac322e9f1a to your computer and use it in GitHub Desktop.
Save datlife/50d89c046f5508ba1fbbe9ac322e9f1a to your computer and use it in GitHub Desktop.
Event Loop
// Async should be first priority over callbacks and promises
//
// High level idea:
// - Avoid .then .catch in promise
// - Syntatic sugar to make async programming similar to sequential code
const axios = require('axios');
DEFAULT_URL = "https://jsonplaceholder.typicode.com"
async function getUser(id) {
let resp = await axios.get(`${DEFAULT_URL}/users/${id}`)
return resp.data
}
async function getUserPosts(id) {
let resp = await axios.get(`${DEFAULT_URL}/users/${id}/posts`)
return resp.data
}
async function getUserWithPosts(id) {
var user = await getUser(id)
let posts = await getUserPosts(id)
user.posts = posts
return user
}
getUserPosts(1)
.then(user => console.log(user))
.catch(err => console.err(`Error ${err}`))
// EVENT LOOP
let A = () => console.log("Running A...")
let B = () => console.log("Running B...")
let C = () => console.log("Running C...")
function work() {
A()
setTimeout(B, 1000) // Non-blocking.. added to Event loop. run after 1s
C()
}
work();
// Expected output:
// $ node event_loop.js
// Running A...
// Running C...
// Running B...
// BLOG PROMISE - CLEAN CODE
// Avoid "modern" promise hell
const axios = require("axios");
DEFAULT_URL = "https://jsonplaceholder.typicode.com"
let getUser = (userId) => {
return axios.default.get(`${DEFAULT_URL}/users/${userId}`)
.then(res => res.data)
}
let getUserPosts = (userId) => {
return axios.default.get(`${DEFAULT_URL}/users/${userId}/posts`)
.then(res => res.data)
}
let getPostComments = postId => {
return axios.default.get(`${DEFAULT_URL}/posts/${postId}/comments`)
.then(res => res.data)
}
let loadPostComments = post => {
return getPostComments(post.id)
.then(comments => {
post.comments = comments
return post
})
}
let getUserWithPosts = (id) => {
var currUser;
return getUser(id)
.then(user => {
currUser = user;
return getUserPosts(id)})
.then(posts => {
return Promise.all(posts.map(post => loadPostComments(post)))})
.then(posts => {
currUser.posts = posts
return currUser})
}
getUserWithPosts(1)
.then(user => console.log(user))
.catch(err => console.log(`Something went wrong ${err}`))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment