Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Javascript Unlocked

You're reading from   Javascript Unlocked Improve your code maintainability, performance, and security through practical expert insights and unlock the full potential of JavaScript

Arrow left icon
Product type Paperback
Published in Dec 2015
Publisher
ISBN-13 9781785881572
Length 182 pages
Edition 1st Edition
Languages
Arrow right icon
Toc

Table of Contents (10) Chapters Close

Preface 1. Diving into the JavaScript Core FREE CHAPTER 2. Modular Programming with JavaScript 3. DOM Scripting and AJAX 4. HTML5 APIs 5. Asynchronous JavaScript 6. A Large-Scale JavaScript Application Architecture 7. JavaScript Beyond the Browser 8. Debugging and Profiling Index

Handling asynchronous functions in the ES7 way


We already have the Promise API in JavaScript. The upcoming technology is Async/Await API and is presented in a proposal (https://tc39.github.io/ecmascript-asyncawait/) for EcmaScript 7th edition. This describes how we can declare asynchronous functions that can halt without blocking anything and wait for the result of Promise:

"use strict";

// Fetch a random joke
function fetchQuote() {
  return fetch( "http://api.icndb.com/jokes/random" )
  .then(function( resp ){
    return resp.json();
  }).then(function( data ){
    return data.value.joke;
  });
}
// Report either a fetched joke or error
async function sayJoke()
{
  try {
    let result = await fetchQuote();
    console.log( "Joke:", result );
  } catch( err ) {
    console.error( err );
  }
}
sayJoke();

At the moment, the API isn't supported in any browser; however, you can run it using the Babel.js transpiler on runtime. You can also fiddle with this example online at http://codepen.io...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image