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
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Advanced JavaScript

You're reading from   Advanced JavaScript Speed up web development with the powerful features and benefits of JavaScript

Arrow left icon
Product type Paperback
Published in Jan 2019
Publisher
ISBN-13 9781789800104
Length 330 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Zachary Shute Zachary Shute
Author Profile Icon Zachary Shute
Zachary Shute
Arrow right icon
View More author details
Toc

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.

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