Coder Social home page Coder Social logo

node-babel-async-await's Introduction

Node.js async/await example

This is a very simple example of how to get async/await working for Node.js. It may work in the browser also, but that is outside the scope of this project.

package.json - NPM configuration

Our NPM configuration is pretty minimal. Basically 2 required dependencies, and a third just for demonstration purposes:

{
  "private": true,
  "dependencies": {
    "babel-preset-latest-minimal": "^1",
    "babel-register": "^6",
    "node-fetch": "^1"
  }
}
  • "private": true - Because we never want to publish this by accident, and it shuts up NPM warnings about required fields.
  • babel-preset-latest-minimal - Gives us only what we need on top of Node.js to support the latest ES2015+ features, including async/await. If you're trying to support the browser, you'll need babel-preset-latest instead.
  • babel-register - Makes it so that when we import a module, it is transformed by Babel before being interpreted.
  • node-fetch - This is just here so that we have something truly asynchronous to demonstrate. It's just fetch() implemented in Node.js.

.babelrc - Babel configuration

Our Babel configuration is tiny, and just specifies which preset to use:

{
    "presets": ["latest-minimal"]
}

Makefile - Task configuration

We need to pass a couple of command-line options to node, so we're using make to take care of them for us:

run: node_modules
    node --harmony --require babel-register index.js

node_modules:
    npm install
  • run: node_modules:
    • This is our default target, named run.
    • Execute it with make run, or just make.
    • It depends on the node_modules target. If node_modules does not exist, the node_modules target will be executed first.
    • node --harmony --require babel-register index.js:
      • node - Should be obvious.
      • --harmony - Enables all the ES2015+ features that node can support out of the box, leaving less for Babel to do.
      • --require babel-register - Loads the babel-register module before interpreting our entry point script, so that it can also be written in ES2015+.
      • index.js - The path to our entry point script.
  • node_modules:
    • This target handles populating our node_modules directory.
    • We don't need to execute it directly, it's automatically taken care of when we execute make run or make.
    • npm install - Installs the NPM dependencies we defined in package.json.

TL;DR

Just run make to see it in action.

index.js - async/await demo

Comments are included in the source:

// Import node-fetch so we have something asynchronous to demonstrate with.
import fetch from 'node-fetch'

// A simple wrapper around fetch() to log the request and response.
async function fetchAndLog(uri) {
    console.log('Fetching ' + uri)

    // These two statements are asynchronous,
    // but look almost like synchronous code.
    const response = await fetch(uri)
    const responseText = await response.text()

    console.log('Received ' + responseText)
}

// It's not possible to use await at the top level, so we need a simple async
// function wrapper.
(async () => {
    // These two operations are executed in series, despite being asynchronous.
    await fetchAndLog('https://httpbin.org/get?request=a')
    await fetchAndLog('https://httpbin.org/get?request=b')

    // These two operations are executed in parallel, and execution resumes when
    // both are finished.
    await Promise.all([
        fetchAndLog('https://httpbin.org/get?request=c'),
        fetchAndLog('https://httpbin.org/get?request=d'),
    ])
})();

Other files

  • node_modules - Node.js stores out dependencies here.
  • .gitignore - Makes Git ignore node_modules.
  • npm-shrinkwrap.json - Makes npm install faster by storing how the dependencies resolved.
  • README.md - See the README.

node-babel-async-await's People

Contributors

ezzatron avatar

Watchers

James Cloos avatar Martial Konvi avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.