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 keysam, and your first name as a database key.If the database entry exists, log the
agefield 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:
Import the database API with
require( ‘./simple_db’ )and save it into the variabledb.Write an async main function. All of the operations will go in here.
Create an array to keep track of the keys that cause
dberrors. Save it into the variablemissingKeys.Create a try-catch block.
Inside the try section, look up the key
johnfrom the database with async/await and thedb.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
johnto themissingKeysarray.Create a second try-catch block.
Inside the try section look up the key
samfrom the database with async/await and thedb.get()functionSave the value into the variable
user.Log the age of the user we looked up.
In the catch section, push the key
samto themissingKeysarray.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
missingKeysarray.In the catch section, insert your
userobject into thedbwith await anddb.insert().In the catch section, create a new try-catch block inside the
catchblock. In the new try section, look up the user we just added to the db with async/await. Save the found user into thevariableuser. Log the age of the user we found. In the catch section, push the key to themissingKeysarray.Outside all of the try-catch blocks, at the end of the main function, return the
missingKeysarray.Call the
mainfunction and attach athen()andcatch()handler to the returned promise.The
then()handler should be passed a function that logs the promise resolution value.The
catch()handler should be passed a function that logs the error’s message field.
Code:
index.jsconst 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.