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...