Book Image

Advanced JavaScript

By : Zachary Shute
3 (1)
Book Image

Advanced JavaScript

3 (1)
By: Zachary Shute

Overview of this book

If you are looking for a programming language to develop flexible and efficient applications, JavaScript is an obvious choice. Advanced JavaScript is a hands-on guide that takes you through JavaScript and its many features, one step at a time. You'll begin by learning how to use the new JavaScript syntax in ES6, and then work through the many other features that modern JavaScript has to offer. As you progress through the chapters, you’ll use asynchronous programming with callbacks and promises, handle browser events, and perform Document Object Model (DOM) manipulation. You'll also explore various methods of testing JavaScript projects. In the concluding chapters, you'll discover functional programming and learn to use it to build your apps. With this book as your guide, you'll also be able to develop APIs using Node.js and Express, create front-ends using React/Redux, and build mobile apps using React/Expo. By the end of Advanced JavaScript, you will have explored the features and benefits of JavaScript to build small applications.
Table of Contents (9 chapters)

Chapter 2: Asynchronous JavaScript


Activity 2 – Using Async/Await

You have been tasked with building a server that interfaces with a database. You must write some code to look up sets and look up basic user objects in the database. Import the simple_db.js file. Using the get and insert commands, write the following program using the async/await syntax:

  • Look up the key called john, the key sam, and your first name as a database key.

  • If the database entry exists, log the age field of the result object.

  • If your name does not exist in the database, insert your name and associate an object containing your first name, last name, and age. Look up the new data association and log the age.

For any db.get operation that fails, save the key into an array. At the end of the program, print the keys that failed.

DB API:

db.get( index ):

This takes in an index and returns a promise. The promise is fulfilled with the db entry associated with that index. If the index does not exist, the db lookup fails, or the key parameter is not specified, the promise is rejected with an error.

db.insert( index, insertData ):

This takes in an index and some data and returns a promise. The promise is fulfilled with the key inserted if the operation completes. If the operation fails, or there is no key or inserted data specified, the promise is rejected with an error.

To utilize promises and the async/await syntax to build a program, follow these steps:

  1. Import the database API with require( ‘./simple_db’ ) and save it into the variable db.

  2. Write an async main function. All of the operations will go in here.

  3. Create an array to keep track of the keys that cause db errors. Save it into the variable missingKeys.

  4. Create a try-catch block.

    Inside the try section, look up the key john from the database with async/await and the db.get() function.

    Save the value into the variable user.

    Log the age of the user we looked up.

    In the catch section, push the key john to the missingKeys array.

  5. Create a second try-catch block.

    Inside the try section look up the key sam from the database with async/await and the db.get() function

    Save the value into the variable user.

    Log the age of the user we looked up.

    In the catch section, push the key sam to the missingKeys array.

  6. Create a third try-catch block.

    Inside the try section, look up the key that is your name from the database with async/await and the db.get() function.

    Save the value into the variable user.

    Log the age of the user we looked up.

    In the catch section, push the key to the missingKeys array.

    In the catch section, insert your user object into the db with await and db.insert().

    In the catch section, create a new try-catch block inside the catch block. In the new try section, look up the user we just added to the db with async/await. Save the found user into the variable user. Log the age of the user we found. In the catch section, push the key to the missingKeys array.

  7. Outside all of the try-catch blocks, at the end of the main function, return the missingKeys array.

  8. Call the main function and attach a then() and catch() handler to the returned promise.

  9. The then() handler should be passed a function that logs the promise resolution value.

  10. The catch() handler should be passed a function that logs the error’s message field.

Code:

index.js
const db = require( './simple_db' );
async function main() {
 const missingKeys = [];
 try { const user = await db.get( 'john' ); } 
 catch ( err ) { missingKeys.push( 'john' ); }
 try { const user = await db.get( 'sam' ); }
 catch ( err ) { missingKeys.push( 'sam' ); }
 try { const user = await db.get( 'zach' ); }
 catch ( err ) {
   missingKeys.push( 'zach' );
   await db.insert('zach', { first: 'zach', last: 'smith', age: 25 });
   try { const user = await db.get( 'zach' ); }
   catch ( err ) { missingKeys.push( 'zach' ); }
 }
 return missingKeys;
}
main().then( console.log ).catch( console.log );

Snippet 2.43: Using async/await

Outcome:

Figure 2.12: Names and ages displayed

You have successfully implemented file-tracking commands and navigated the repository's history.