Skip to content

Instantly share code, notes, and snippets.

@davepoon
Forked from wesbos/async-await.js
Created February 15, 2018 00:32
Show Gist options
  • Select an option

  • Save davepoon/11b56b01cff3981937265d3d340f1414 to your computer and use it in GitHub Desktop.

Select an option

Save davepoon/11b56b01cff3981937265d3d340f1414 to your computer and use it in GitHub Desktop.

Revisions

  1. @wesbos wesbos created this gist Feb 22, 2017.
    32 changes: 32 additions & 0 deletions async-await.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    // 🔥 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('https://api.github.com/users/wesbos');
    console.log(wes.data); // mediocre code
    // many requests should be concurrent - don't slow things down!
    // fire off three requests and save their promises
    const wordPromise = axios('http://www.setgetgo.com/randomword/get.php');
    const userPromise = axios('https://randomuser.me/api/');
    const namePromise = axios('https://uinames.com/api/');
    // 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(word.data, user.data, name.data); // cool, {...}, {....}
    } catch (e) {
    console.error(e); // 💩
    }
    }

    go();