Comment

Comment by nailer

Short ver: async await is now in an LTS release of node. Anything that returns a promise can now be run inline - ie, no endless .then() chaining - provided you've started an async context:

  const writeFile = util.promisify(fs.writeFile),
    request = util.promisify('superagent'),
    stat = util.promisify(fs.stat),
    sorts = require('sorts'),
    log = console.log.bind(console)

  const getJeansAndSaveThem = async function(){ 
    var jeans = await request.get('https://example.com/api/v1/product/trousers').query({
      label: 'Levi Strauss', 
      isInStock: true,
      maxResults: 500
    }).end()
    jeans = jeans.sort(sorts.alphabetical)
    await writeFile('jeans.json', jeans)
    const status = await stat('jeans.json');
    log(`I just got some data from an API and saved the results to a file. The file was born at ${status.birthtime}`)
  }
Note: you should add error handling, I'm new to async/await and this code is to demonstrate a concept on HN, not to run your life support system. ;-)
parent nailer 9 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton