• Stars
    star
    156
  • Rank 238,161 (Top 5 %)
  • Language
    JavaScript
  • Created over 9 years ago
  • Updated about 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Playing around with ES7 async functions

es7-async

Playing around with ES7 async functions

Case study

In this case study our program must load 3 resources (json files). The requests must to be chained, one after another, logging the output for each request success.

Old friend Ajax

First, let's look how we can accomplish the mission with our old friend Ajax. The ajax function is responsible for creating an xhr object and execute the callback returning the data. No big deal here, we have done this a lot in the past, right?

// Getting data
ajax('data.json', (data) => {
	console.log('AJAX/data >>>', JSON.parse(data));

	// Getting users
	ajax('users.json', (users) => {
		console.log('AJAX/users >>>', JSON.parse(users));

		// Getting products
		ajax('products.json', (products) => {
			console.log('AJAX/products >>>', JSON.parse(products));
		});
	});
});

Not so new friend, Promises

Promises are around for a while, and now it is part of the ECMAScript 6º edition. With promises we eliminate the pyramid of doom (callback hell), having a much more cleaner code. Check it out:

// Promises
// Wrap the ajax function to return promises
function requestP(url) {
	return new Promise(function(resolve, reject) {
		ajax(url, (response) => {
			resolve(JSON.parse(response));
		});
	});
}

// Getting data
requestP('data.json')
.then(function(data){
	console.log('Promises/data >>>', data);
});

// Getting users
requestP('users.json')
.then(function(users){
	console.log('Promises/users >>>', users);
});

// Getting products
requestP('products.json')
.then(function(products){
	console.log('Promises/products >>>', products);
});

With promises, we can easily have parallel execution:

// Parallel operations with promises
// Getting data, users and products
Promise.all([
	requestP('data.json'),
	requestP('users.json'),
	requestP('products.json')
])
.then(function(data) {
	console.log('Parallel promises >>>', data);
});

The fetch API is the new Ajax substitute. We have a lot of new features and a very nice promise-based API:

// Promises with the fetch API
// Getting data
fetch('data.json')
.then(function(data) {
	return data.json();
})
.then(function(data) {
	console.log('Promises+fetch/data >>>', data);
});

// Getting users
fetch('users.json')
.then(function(data) {
	return data.json();
})
.then(function(users) {
	console.log('Promises+fetch/users >>>', users);
});

// Getting products
fetch('products.json')
.then(function(data){
	return data.json();
})
.then(function(products) {
	console.log('Promises+fetch/products >>>', products);
});

New powerful friend, generators

Generators basically are functions that can have their execution paused. Take a look on what we can do with generators:

// Generators
function request(url) {
	ajax(url, (response) => {
		iterator.next(JSON.parse(response));
	});
}

function *main() {
	// Getting data
	let data = yield request('data.json');

	// Getting users
	let users = yield request('users.json');

	// Getting products
	let products = yield request('products.json');

	console.log('Generator/data >>>', data);
	console.log('Generator/users >>>', users);
	console.log('Generator/products >>>', products);
}

var iterator = main();
iterator.next();

The new awesome beast, async functions

With async functions, we can await on Promises. Take a look (awesomeness alert):

(async () => {
	// Getting data
	let data = await requestP('data.json');

	// Getting users
	let users = await requestP('users.json');

	// Getting products
	let products = await requestP('products.json');

	console.log('ES7 Async/data >>>', data);
	console.log('ES7 Async/users >>>', users);
	console.log('ES7 Async/products >>>', products);
})();

With the fetch API:

(async () => {
// Async/await using the fetch API
	try {

		// Getting data
		let data = await fetch('data.json');

		// Parsing data
		let parsedData = await data.json();

		// Getting users
		let users = await fetch('users.json');

		// Parsing users
		let parsedUsers = await users.json();

		// Getting products
		let products = await fetch('products.json');

		// Parsing products
		let parsedProducts = await products.json();


		console.log('ES7 Async+fetch/data >>>', parsedData);
		console.log('ES7 Async+fetch/users >>>', parsedUsers);
		console.log('ES7 Async+fetch/products >>>', parsedProducts);


	} catch (error) {
		console.log(error);
	}
})();

Parallel operations with async:

(async () => {
	let parallelData = await Promise.all([
		requestP('data.json'),
		requestP('users.json'),
		requestP('products.json')
	]);
	console.log('Async parallel >>>', parallelData);
})();

Parallel operations with async + fetch (Oh my god this is great!):

(async () => {
	let parallelDataFetch = await Promise.all([
		(await fetch('data.json')).json(),
		(await fetch('users.json')).json(),
		(await fetch('products.json')).json()
	]);
	console.log('Async parallel+fetch >>>', parallelDataFetch);
})();

How to run this experiment

npm install
grunt

Serve the dist folder, open the /sample/index.html and check it out you dev-tools console.

References

http://jakearchibald.com/2014/es7-async-functions/ http://pouchdb.com/2015/03/05/taming-the-async-beast-with-es7.html http://www.sitepoint.com/simplifying-asynchronous-coding-es7-async-functions/

More Repositories

1

es2020

ES2020 examples
JavaScript
35
star
2

js-future-in-the-present

JavaScript's future in the present
JavaScript
16
star
3

tweets-to-md

Convert tweets to markdown
JavaScript
16
star
4

marked-metadata

Markdown parser (using marked) with metadata header support
JavaScript
9
star
5

DojoPOA

Codes that were made in DojoPOA
8
star
6

simple-css3-cube-3d

Is just a simple CSS3 3D cube with no JavaScript
7
star
7

web-notification-sample

WebNotification Sample
JavaScript
6
star
8

femug

Guidelines for "Front-End Meet-Up Group" project
6
star
9

es6slider

ES6 presentation tool
JavaScript
5
star
10

wasm-test

Hacking with wasm
JavaScript
5
star
11

simple-css3-sphere-3d

Simple CSS3 3D Sphere
JavaScript
5
star
12

QUnitTestMachine

A QUnit based test library to simplify Javascript tests
JavaScript
5
star
13

react-native-test

React Native Demo with Facebook Login
JavaScript
5
star
14

react-6to5

Playing with react and 6to5
JavaScript
4
star
15

jaydson.com

The source code for my personal website (using Hugo static site generator)
HTML
4
star
16

richblocks

Final work in college back in 2006
HTML
3
star
17

jquery.rotate.js

A jQuery cssHooks adding a cross browser 'rotate' property to $.fn.css() and $.fn.animate().
JavaScript
3
star
18

myscraper

MyScrap is web scraping experiment with node
JavaScript
3
star
19

iojs-test

Testing native ES6 with iojs
JavaScript
3
star
20

criando-uma-aplicacao-moderna-com-graphql-e-node.js-template

The template repository for the Criando uma aplicação moderna com GraphQL e Node.js course on Learning Lab.
3
star
21

twitter.jaydson.com

The new home for my tweets
HTML
3
star
22

speaker-space-ember

Ember's implementation of Speaker Space project
JavaScript
2
star
23

html5-history-api-devderby

Simple HTML5 history API demo to Mozilla DevDerby
2
star
24

MuiToZF

MochaUI to Zend Framework - Simple RIA Applications with Mocha UI and ZF
2
star
25

json-image-pagination

jQuery Plugin to create an dynamic image pagination
JavaScript
1
star
26

react-example

Testing react
JavaScript
1
star
27

dotfiles

My dotfiles
Shell
1
star
28

require-from-esm

Require CJS modules from ES modules
JavaScript
1
star
29

manifesto

1
star
30

react-example-2

Playing with react 13 (native ES6 classes support)
JavaScript
1
star
31

jaydson.org-wordpress-theme-2.0

Wordpress theme for jaydson.org Blog 2.0
PHP
1
star
32

speaker-space-react

React's implementation of Speaker Space project
JavaScript
1
star
33

hugo-paper-tailwind

Hugo Paper Tailwind theme
HTML
1
star
34

react-static

Just playing with React on the server.
JavaScript
1
star
35

es6-modules-6to5

ES6 modules with 6to5
JavaScript
1
star
36

jaydson-ghost-theme

Custom Ghost theme for my personal Blog
CSS
1
star
37

wall-explosion-css3d

Wall Explosion is an CSS3 3D experiment
JavaScript
1
star
38

webapp-scoreboard

Webapp ScoreBoard is an app created for fossball players
JavaScript
1
star
39

transpileception

Transpiling JavaScript to transpile JavaScript to JavaScript
CoffeeScript
1
star
40

harmonic-theme-jaydson-2016

My new blog theme
CSS
1
star
41

next-blog-starter

Generated by https://bohr.io
TypeScript
1
star
42

Kactoos-Puzzle

Simple Kactoos Puzzle. Kactoos API demonstration
PHP
1
star
43

fetch

Github's window.fetch polyfill in ES6
JavaScript
1
star
44

math-experiments

Just playing around with some math formulas my girlfriend is using on her remote sensing master degree
JavaScript
1
star
45

Kactoos-API

PHP classes abstraction for Kactoos API
PHP
1
star
46

jaydson

My GitHub personal profile
1
star
47

trashy-net-checker

Oh my. My internet provider is so trashy. I want to check how trashy my connection is.
1
star
48

next-test

Trying out Nextjs
JavaScript
1
star
49

talks

My talks
JavaScript
1
star
50

hyperterm-theme-braziljs

Hyperterm theme BrazilJS
1
star
51

Ajax-Developer-Debug

Ajax Developer Debug is a plugin for debugging XMLHttpRequest requests. The plugin allows you to capture all the errors returned by Ajax on jQuery. This plugin can be used in a development environment to show errors at runtime, or even enter these errors in an HTML element in your Web Application.
1
star