ES7+ Async Flow (async await) *syntactic sugar
JS
S
JavaScriptSnippet to create an asynchronous flow in a synchronous code format. Note: to run this feature, please use Node v7.9 or use the latest version of Babel to transpile (Babel Core v7.0). *ensure 'babel-preset-es2017' is installed.
1async function createGameFlow(cb){
2 try {
3 const game = await createGame();
4 const environment = await selectEnvironment(game);
5 game.environment = environment;
6 await saveGame(game);
7 return cb(undefined, game);
8 } catch (ex) {
9 return cb(ex);
10 }
11}
12
13async function createGame(){
14 return new Promise((res) => {
15 console.log("Creating game...");
16 setTimeout(() => {
17 return res({title: "Casino Poker Game"});
18 }, 500);
19 });
20}
21
22async function selectEnvironment(game){
23 return new Promise((res) => {
24 console.log("Selecting game environment...");
25 setTimeout(() => {
26 return res({environemnt: "ios, android"});
27 }, 500);
28 });
29}
30
31async function saveGame(employee){
32 return new Promise((res) => {
33 console.log("Saving game to DB...");
34 setTimeout(() => {
35 return res();
36 }, 500);
37 });
38}
39
40createGameFlow((err, game) => {
41 if(err) {
42 console.error('error', err);
43 } else{
44 console.log('Game Created and Saved', game);
45 }
46 console.log('exiting..');
47 process.exit();
48});Created on 6/14/2017