Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Simple Async/Await Example
// 🔥 Node 7.6 has async/await! Here is a quick run down on how async/await works
const axios = require('axios'); // promised based requests - like fetch()
function getCoffee() {
return new Promise(resolve => {
setTimeout(() => resolve(''), 2000); // it takes 2 seconds to make coffee
async function go() {
try {
// but first, coffee
const coffee = await getCoffee();
console.log(coffee); //
// then we grab some data over an Ajax request
const wes = await axios('');
console.log(; // mediocre code
// many requests should be concurrent - don't slow things down!
// fire off three requests and save their promises
const wordPromise = axios('');
const userPromise = axios('');
const namePromise = axios('');
// await all three promises to come back and destructure the result into their own variables
const [word, user, name] = await Promise.all([wordPromise, userPromise, namePromise]);
console.log(,,; // cool, {...}, {....}
} catch (e) {
console.error(e); // 💩
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.