Search code examples
ecmascript-6ecmascript-2016

What is this syntax in ES6 or ES7?


I came across this syntax which I believe is ES6 or ES7. What do these lines of code do?

module.exports = async (taskData) => {
  // do stuff
}

Solution

  • It exports an asynchronous arrow function which takes in an argument taskData. The asynchronous function is new syntax that is set to come with this year's release, ES2017, called the async function, though the rest of the code is ES6 (ES2015) and ES5 (ES2011). It goes hand-in-hand with await and returns a Promise.

    It's primarily useful to clean up promise chains, where the code can get really messy. Consider this example using promises, found here:

    function loadStory() {
      return getJSON('story.json').then(function(story) {
        addHtmlToPage(story.heading);
    
        return story.chapterURLs.map(getJSON)
          .reduce(function(chain, chapterPromise) {
            return chain.then(function() {
              return chapterPromise;
            }).then(function(chapter) {
              addHtmlToPage(chapter.html);
            });
          }, Promise.resolve());
      }).then(function() {
        addTextToPage("All done");
      }).catch(function(err) {
        addTextToPage("Argh, broken: " + err.message);
      }).then(function() {
        document.querySelector('.spinner').style.display = 'none';
      });
    }
    

    The example above fetches a story, and iterates through all the chapters and adds them to the HTML. It works, but it can be very messy and hard to follow if you've got lots of stuff to do. Instead, you can use async and await, which is just syntactic sugar, but makes it much more clean:

    async function loadStory() {
      try {
        let story = await getJSON('story.json');
        addHtmlToPage(story.heading);
        for (let chapter of story.chapterURLs.map(getJSON)) {
          addHtmlToPage((await chapter).html);
        }
        addTextToPage("All done");
      } catch (err) {
        addTextToPage("Argh, broken: " + err.message);
      }
      document.querySelector('.spinner').style.display = 'none';
    }
    

    The above is (in my opinion) way more clean and easy to follow, versus the messy promise chain in the first example.