Skip to content

Instantly share code, notes, and snippets.

@mpj
Created August 14, 2017 07:38
Show Gist options
  • Star 38 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save mpj/3f8bc0c6ecda4294fbeff99f1e3fae85 to your computer and use it in GitHub Desktop.
Save mpj/3f8bc0c6ecda4294fbeff99f1e3fae85 to your computer and use it in GitHub Desktop.
Code for the async/await episode of Fun Fun Function.
const response = await fetch(`https://catappapi.herokuapp.com/users/${userId}`)
const data = await response.json()
return data.imageUrl
}
const response = await fetch(`https://catappapi.herokuapp.com/users/${userId}`)
const data = await response.json()
return data.imageUrl
}
function fetchCatAvatars(userId) {
return fetch(`https://catappapi.herokuapp.com/users/${userId}`)
.then(response => response.json())
.then(user => {
const promises = user.cats.map(catId =>
fetch(`https://catappapi.herokuapp.com/cats/${catId}`)
.then(response => response.json())
.then(catData => catData.imageUrl))
return Promise.all(promises)
})
}
async function fetchCatAvatars(userId) {
const response = await fetch(`http://catappapi.herokuapp.com/users/${userId}`)
const user = await response.json()
const catImageUrls = []
for (const catId of user.cats) {
const response = await fetch(`http://catappapi.herokuapp.com/cats/${catId}`)
const catData = await response.json()
catImageUrls.push(catData.imageUrl)
}
return catImageUrls
}
async function fetchCatAvatars(userId) {
const response = await fetch(`http://catappapi.herokuapp.com/users/${userId}`)
const user = await response.json()
return await Promise.all(user.cats.map(async function(catId) {
const response = await fetch(`http://catappapi.herokuapp.com/cats/${catId}`)
const catData = await response.json()
return catData.imageUrl
}))
}
async function fetchCatAvatars(userId) {
const response = await fetch(`http://catappapi.herokuapp.com/users/${userId}`)
const user = await response.json()
return await Promise.all(user.cats.map(async function(catId) {
const response = await fetch(`http://catappapi.herokuapp.com/cats/${catId}`)
const catData = await response.json()
return catData.imageUrl
}))
}
const processUser = require('imaginary_service/process_user')
async function processAllUsers () {
const sql = 'SELECT id FROM users'
const users = await db.query(sql, [])
for (const user of users) {
await processUser(user.id)
}
}
const processUser = require('imaginary_service/process_user')
function processAllUsers () {
const sql = 'SELECT id FROM users'
return db.query(sql, [])
.then(users =>
users.reduce((lastPromise, user) =>
lastPromise.then(_ => processUser(user.id))
, Promise.resolve()))
}
var restify = require('restify')
const corsMiddleware = require('restify-cors-middleware')
const db = {
users: {
'123': {
name: 'mpj',
cats: [ 21, 33, 45 ],
imageUrl: 'http://images.somecdn.com/user-123.jpg'
}
},
cats: {
'21': {
name: 'Fluffykins',
imageUrl: 'http://images.somecdn.com/cat-21.jpg',
},
'33': {
name: 'Waffles',
imageUrl: 'http://images.somecdn.com/cat-33.jpg'
},
'45': {
name: 'Sniffles',
imageUrl: 'http://images.somecdn.com/cat-45.jpg'
}
}
}
function cats(req, res, next) {
res.send(db.cats[req.params.id])
next()
}
function users(req, res, next) {
res.send(db.users[req.params.id])
next()
}
var server = restify.createServer()
const cors = corsMiddleware({
origins: ['*']
})
server.pre(cors.preflight)
server.use(cors.actual)
server.get('/cats/:id', cats)
server.get('/users/:id', users)
server.listen(process.env.PORT || 8080, function() {
console.log('%s listening at %s', server.name, server.url)
})
@MarkShulhin
Copy link

Hi! I was writing in VS Code these examples but my Quokka didn't recognize the async/await keywords... Do I need to install something else globally through npm or something like that? Thanks for your videos!

@Archangel212
Copy link

@MarkShulhin In my case i need to update my node js version to the current stable version v8.4.0, and it works.

@aboglioli
Copy link

In example05 and example06:

 return await Promise.all(user.cats.map(async function(catId) {
   // ...
 }))

is the same as:

 return Promise.all(user.cats.map(async function(catId) { // without await
   // ...
 }))

Because Promise.all() returns a Promise without await keyword. If you use await you will return a value instead of a promise. It works as well but there is a little difference behind.

Great show @mpj! I'm a big fan of yours.

@rsrinivasanhome
Copy link

Any reason why example01.js and example02.js are the same ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment