JavaScript and TypeScript course ยท Module 4: Asynchronous JavaScript

Async/Await - Elegant Asynchronous Code

17 min read ยท
In this lesson14

In previous exercises we learned about callbacks and Promises. Now it is time to learn about async/await - syntax introduced in ES2017 that makes asynchronous code look and behave almost like synchronous code.

In Jurassic Park, imagine you are a scientist who needs to: collect a DNA sample, sequence it, synthesize a protein, grow cells, and finally create a dinosaur. With async/await this process reads like a straightforward step-by-step procedure, even though each step is asynchronous!

The async Keyword

Placing async before a function declaration makes it an async function. An async function:

  • Always returns a Promise (even if you return a plain value)
  • Can use the await keyword inside its body
// Regular function - returns undefined
function getName() {
  return "Rexy";
}

// Async function - returns Promise<string>
async function getDinosaurName() {
  return "Rexy";  // Automatically wrapped in Promise.resolve("Rexy")
}

getName();                  // "Rexy"
getDinosaurName();          // Promise { 'Rexy' }
getDinosaurName().then(name => console.log(name)); // "Rexy"

The await Keyword

await can only be used inside an async function. It pauses execution of the async function until the Promise settles, then resumes with the resolved value.

function fetchDinosaurData(id) {
  return new Promise(resolve => {
    setTimeout(() => resolve({ id, name: "Blue", species: "Velociraptor", health: 98 }), 1000);
  });
}

// Without async/await - using .then()
function showDinoInfoOld(id) {
  return fetchDinosaurData(id).then(dino => {
    console.log(`${dino.name} (${dino.species}) - health: ${dino.health}%`);
    return dino;
  });
}

// With async/await - reads like synchronous code
async function showDinoInfo(id) {
  const dino = await fetchDinosaurData(id); // Pauses here until Promise resolves
  console.log(`${dino.name} (${dino.species}) - health: ${dino.health}%`);
  return dino;
}

showDinoInfo(1);

Comparison: Promise Chains vs async/await

Let's compare the same functionality implemented with traditional Promise syntax and async/await:

// Using traditional Promises
function checkSecuritySystems() {
  console.log("Checking security systems...");

  return fetchGateStatus()
    .then(gateStatus => {
      console.log("Gate status:", gateStatus.allClosed ? "All closed" : "WARNING! Some are open");

      return fetchFenceStatus();
    })
    .then(fenceStatus => {
      console.log("Fence:", fenceStatus.power > 8000 ? "Secured" : "Insufficient power!");

      return fetchCameraStatus();
    })
    .then(cameraStatus => {
      console.log("Cameras:", cameraStatus.allOperational ? "All operational" : "Some are not working!");

      return {
        gate: gateStatus,
        fence: fenceStatus,
        cameras: cameraStatus,
        checkDuration: new Date().toISOString()
      };
    })
    .catch(error => {
      console.error("Error during check:", error.message);
      throw new Error(`Check failed: ${error.message}`);
    });
}

// Using async/await
async function checkSecuritySystems() {
  console.log("Checking security systems...");

  try {
    // Each of the following calls pauses function execution
    const gateStatus = await fetchGateStatus();
    console.log("Gate status:", gateStatus.allClosed ? "All closed" : "WARNING! Some are open");

    const fenceStatus = await fetchFenceStatus();
    console.log("Fence:", fenceStatus.power > 8000 ? "Secured" : "Insufficient power!");

    const cameraStatus = await fetchCameraStatus();
    console.log("Cameras:", cameraStatus.allOperational ? "All operational" : "Some are not working!");

    return {
      gate: gateStatus,
      fence: fenceStatus,
      cameras: cameraStatus,
      checkDuration: new Date().toISOString()
    };
  } catch (error) {
    console.error("Error during check:", error.message);
    throw new Error(`Check failed: ${error.message}`);
  }
}

Notice that:

  • Code using async/await is significantly more readable - it looks almost like synchronous code
  • It is easier to track the data flow (values gateStatus, fenceStatus, cameraStatus)
  • Error handling is simpler, using standard try/catch syntax instead of .catch()

Converting Promise-Returning Functions to async/await

Any function that returns a Promise can be transformed into an async function:

// Function returning a Promise
function measureEnclosureTemperature(enclosureId) {
  return new Promise((resolve, reject) => {
    // Measurement code...
  });
}

// Transformed to async function
async function measureEnclosureTemperature(enclosureId) {
  // We can use asynchronous operations with await
  const sensor = await connectToSensor(enclosureId);
  const reading = await sensor.getTemperature();

  if (reading.status === "error") {
    throw new Error(`Temperature reading error: ${reading.message}`);
  }

  return {
    enclosureId,
    temperature: reading.value,
    unit: "Celsius",
    measurementTime: new Date()
  };
}

Error Handling with try/catch

Instead of .catch(), async functions use regular try/catch:

async function performHealthCheck(dinoId) {
  try {
    const dino = await fetchDinosaurData(dinoId);
    const enclosure = await fetchEnclosureStatus(dino.enclosureId);
    const vetReport = await fetchVetReport(dinoId);

    return {
      dinosaur: dino.name,
      enclosureOk: enclosure.status === "secure",
      lastCheckup: vetReport.date,
      overall: "healthy"
    };
  } catch (error) {
    console.error(`Health check failed for dinosaur ${dinoId}: ${error.message}`);
    return { dinosaur: dinoId, overall: "unknown", error: error.message };
  } finally {
    console.log(`Health check routine complete for dinosaur ${dinoId}`);
  }
}

// Stub functions
function fetchEnclosureStatus(id) {
  return Promise.resolve({ id, status: "secure", lastInspected: "2024-01-15" });
}
function fetchVetReport(id) {
  return Promise.resolve({ dinoId: id, date: "2024-01-10", notes: "All clear" });
}

performHealthCheck(42).then(report => console.log(report));

Detailed Error Handling Example

async function releaseDinosaurFromEnclosure(dinoId, enclosureId) {
  try {
    // Check if we have permissions
    const permissions = await checkPermissions();
    if (!permissions.canReleaseAnimals) {
      throw new Error("No permission to release dinosaurs");
    }

    // Check dinosaur status
    const dinosaurStatus = await checkDinosaurStatus(dinoId);
    if (dinosaurStatus.health !== "Good") {
      throw new Error(`Dinosaur #${dinoId} is not in good health`);
    }

    // Check if the enclosure is secure
    const enclosureStatus = await checkEnclosureStatus(enclosureId);
    if (!enclosureStatus.isSecure) {
      throw new Error(`Enclosure #${enclosureId} is not safe`);
    }

    // Open the enclosure gate
    await openEnclosureGateById(enclosureId);
    console.log(`Gate of enclosure #${enclosureId} opened`);

    // Release the dinosaur
    const result = await transferDinosaur(dinoId, enclosureId, "outdoor-area");
    console.log(`Dinosaur #${dinoId} has been released to the outdoor area of enclosure #${enclosureId}`);

    return {
      success: true,
      message: `Dinosaur #${dinoId} has been successfully released`,
      details: result
    };
  } catch (error) {
    console.error("Dinosaur release operation failed:", error.message);

    // We can attempt to fix the error or perform cleanup operations
    try {
      await closeAllGates();
      await activateSecuritySystem();
    } catch (cleanupError) {
      console.error("Error during cleanup operations:", cleanupError.message);
    }

    return {
      success: false,
      message: `Error while releasing dinosaur: ${error.message}`,
      error: error.message
    };
  }
}

In the above example we used a try/catch block to handle any errors that may occur during the dinosaur release process. We can also nest try/catch blocks, as seen in the error handler where we attempt cleanup operations that may also fail.

Asynchronous Iterations

The introduction of async/await also enabled asynchronous iterations, which are particularly useful when working with collections of objects that require asynchronous operations.

Sequential Collection Processing

async function examineAllDinosaurs(idList) {
  console.log(`Starting examination of ${idList.length} dinosaurs...`);

  const results = [];

  // Sequential processing (one after another)
  for (const id of idList) {
    try {
      const result = await examineDinosaur(id);
      console.log(`Dinosaur #${id} examined: ${result.status}`);
      results.push({
        id,
        success: true,
        result: result
      });
    } catch (error) {
      console.error(`Error examining dinosaur #${id}: ${error.message}`);
      results.push({
        id,
        success: false,
        error: error.message
      });
    }
  }

  return {
    totalExaminations: idList.length,
    successful: results.filter(w => w.success).length,
    unsuccessful: results.filter(w => !w.success).length,
    results
  };
}

In the above example we use for...of with await inside the loop, which causes dinosaur examinations to be performed one after another. This is the appropriate approach when order matters or when operations must be performed sequentially.

Parallel Collection Processing

If operations don't need to be performed sequentially, it's often better to process the collection in parallel:

async function examineAllDinosaursInParallel(idList) {
  console.log(`Starting examination of ${idList.length} dinosaurs in parallel...`);

  // Creating an array of promises
  const promises = idList.map(id => {
    return examineDinosaur(id)
      .then(result => ({
        id,
        success: true,
        result: result
      }))
      .catch(error => ({
        id,
        success: false,
        error: error.message
      }));
  });

  // Parallel execution of all examinations
  const results = await Promise.all(promises);

  return {
    totalExaminations: idList.length,
    successful: results.filter(w => w.success).length,
    unsuccessful: results.filter(w => !w.success).length,
    results
  };
}

In this case we use map() to create an array of Promises and then use Promise.all() with await to wait for all operations to complete. This way all examinations are performed in parallel, which can significantly speed up the processing of large collections.

Parallel Processing with a Limit

Sometimes we don't want to perform all operations simultaneously as that could overload the system. In such cases we can limit the number of parallel operations:

async function examineDinosaursWithLimit(idList, maxParallel = 3) {
  console.log(`Starting examination of ${idList.length} dinosaurs (max ${maxParallel} in parallel)...`);

  const results = [];

  // Processing in batches
  for (let i = 0; i < idList.length; i += maxParallel) {
    const batch = idList.slice(i, i + maxParallel);
    console.log(`Processing batch ${Math.floor(i / maxParallel) + 1} (${batch.length} dinosaurs)...`);

    // Creating promise array for the current batch
    const batchPromises = batch.map(id => {
      return examineDinosaur(id)
        .then(result => ({
          id,
          success: true,
          result: result
        }))
        .catch(error => ({
          id,
          success: false,
          error: error.message
        }));
    });

    // Parallel execution of examinations in the current batch
    const batchResults = await Promise.all(batchPromises);
    results.push(...batchResults);

    console.log(`Batch ${Math.floor(i / maxParallel) + 1} completed.`);
  }

  return {
    totalExaminations: idList.length,
    successful: results.filter(w => w.success).length,
    unsuccessful: results.filter(w => !w.success).length,
    results
  };
}

In this case we process the ID list in batches of maxParallel elements. Each batch is processed in parallel, but we wait for all operations in one batch to complete before moving to the next.

Sequential vs Parallel Execution

One of the most important concepts with async/await is knowing when execution is sequential and when it is parallel:

// SEQUENTIAL - each awaits before the next starts
async function sequentialCheck() {
  console.time("sequential");
  const fence = await checkFenceSystem("A");   // ~1 second
  const camera = await checkCameraSystem("North"); // ~1 second
  const sensor = await checkMotionSensors("B");    // ~1 second
  console.timeEnd("sequential"); // ~3 seconds total
  return [fence, camera, sensor];
}

// PARALLEL - all start at the same time, await all results
async function parallelCheck() {
  console.time("parallel");
  const [fence, camera, sensor] = await Promise.all([
    checkFenceSystem("A"),
    checkCameraSystem("North"),
    checkMotionSensors("B")
  ]);
  console.timeEnd("parallel"); // ~1 second total
  return [fence, camera, sensor];
}

// Stub functions
function checkFenceSystem(id) { return new Promise(res => setTimeout(() => res({ sector: id, ok: true }), 800)); }
function checkCameraSystem(id) { return new Promise(res => setTimeout(() => res({ zone: id, ok: true }), 900)); }
function checkMotionSensors(id) { return new Promise(res => setTimeout(() => res({ area: id, ok: true }), 700)); }

Rule of thumb:

  • Use await one-by-one only when each operation depends on the result of the previous one
  • Use Promise.all() with await when operations are independent - it is much faster
async function prepareDinoReport(dinoId) {
  // Step 1: Must happen first (ID needed for step 2)
  const dino = await fetchDinosaurData(dinoId);

  // Steps 2-4 are independent of each other - run in parallel
  const [enclosure, vetRecord, feedingLog] = await Promise.all([
    fetchEnclosureStatus(dino.enclosureId),
    fetchVetReport(dino.id),
    fetchFeedingLog(dino.id)
  ]);

  return { dino, enclosure, vetRecord, feedingLog };
}

function fetchFeedingLog(id) {
  return Promise.resolve({ dinoId: id, lastFed: "2024-01-15 08:00", amount: "50kg" });
}

Async Arrow Functions and Class Methods

async works with all function forms:

// Async arrow function
const getDinoStatus = async (id) => {
  const data = await fetchDinosaurData(id);
  return data.health > 80 ? "healthy" : "needs attention";
};

// Async class method
class DinoMonitor {
  constructor(parkId) {
    this.parkId = parkId;
  }

  async runFullScan() {
    console.log(`Starting full scan of park ${this.parkId}...`);
    const results = await Promise.all([
      this.checkAllFences(),
      this.checkAllCameras()
    ]);
    return results;
  }

  async checkAllFences() {
    // Simulate checking fences
    await new Promise(res => setTimeout(res, 600));
    return { fences: "all secure", checked: 24 };
  }

  async checkAllCameras() {
    await new Promise(res => setTimeout(res, 400));
    return { cameras: "all online", checked: 48 };
  }
}

const monitor = new DinoMonitor("JP-001");
monitor.runFullScan().then(results => console.log("Scan results:", results));

Detailed Class Example: Dinosaur Monitoring System

class DinosaurMonitoringSystem {
  constructor(sector) {
    this.sector = sector;
    this.active = false;
    this.dinosaurs = [];
  }

  async initialize() {
    try {
      // Fetch dinosaur list in the sector
      const list = await fetchDinosaurListInSector(this.sector);
      this.dinosaurs = list;

      // Initialize sensors
      await this.initializeSensors();

      this.active = true;
      console.log(`Monitoring system for sector ${this.sector} initialized`);

      return true;
    } catch (error) {
      console.error(`Monitoring system initialization error: ${error.message}`);
      return false;
    }
  }

  async initializeSensors() {
    // Initialize sensors for each dinosaur
    const promises = this.dinosaurs.map(dino =>
      initializeSensorForDinosaur(dino.id)
    );

    return Promise.all(promises);
  }

  async monitor(monitoringDuration = 60000) {
    if (!this.active) {
      throw new Error("Monitoring system is not active");
    }

    console.log(`Starting monitoring of sector ${this.sector} for ${monitoringDuration/1000} seconds...`);

    // Monitor for a specified time
    const startTime = Date.now();

    while (Date.now() - startTime < monitoringDuration) {
      // Fetch status of all dinosaurs
      const statuses = await Promise.all(
        this.dinosaurs.map(dino => checkDinosaurStatus(dino.id))
      );

      // Analyze statuses
      const abnormalDinosaurs = statuses.filter(s => s.status !== "normal");

      if (abnormalDinosaurs.length > 0) {
        console.warn(`Detected ${abnormalDinosaurs.length} dinosaurs with abnormal status!`);

        for (const status of abnormalDinosaurs) {
          console.warn(`Dinosaur #${status.dinoId}: ${status.status} - ${status.details}`);

          // Send alert for each abnormal status
          await sendAlert(this.sector, status);
        }
      }

      // Wait 5 seconds before the next check
      await new Promise(resolve => setTimeout(resolve, 5000));
    }

    console.log(`Monitoring of sector ${this.sector} completed.`);
    return `Monitoring completed: ${new Date().toISOString()}`;
  }
}

// Using the class
async function startMonitoringSystem(sector) {
  const system = new DinosaurMonitoringSystem(sector);

  const initializationSuccessful = await system.initialize();
  if (!initializationSuccessful) {
    console.error(`Failed to initialize the system for sector ${sector}`);
    return;
  }

  // Monitor for 5 minutes
  await system.monitor(300000);

  console.log(`Monitoring session for sector ${sector} completed`);
}

Async IIFE (Immediately Invoked Function Expression)

Sometimes you need to run async code at the top level (outside any async function). Use an async IIFE:

// Immediately runs the async function
(async () => {
  try {
    const status = await getDinoStatus(7);
    console.log("Status:", status);

    const report = await prepareDinoReport(7);
    console.log("Report ready for dinosaur:", report.dino.name);
  } catch (error) {
    console.error("Top-level error:", error.message);
  }
})();

Recursive Async Functions

Async functions can call themselves recursively:

async function retryOperation(operation, maxRetries, delay = 500) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      const result = await operation();
      console.log(`Success on attempt ${attempt}`);
      return result;
    } catch (error) {
      console.log(`Attempt ${attempt} failed: ${error.message}`);
      if (attempt === maxRetries) throw error;
      await new Promise(res => setTimeout(res, delay * attempt)); // Exponential-ish backoff
    }
  }
}

// Usage - retry sensor read up to 3 times
async function readUnreliableSensor(sensorId) {
  return retryOperation(
    () => new Promise((resolve, reject) => {
      setTimeout(() => {
        Math.random() > 0.6
          ? resolve({ sensorId, value: Math.random() * 100 })
          : reject(new Error(`Sensor ${sensorId} did not respond`));
      }, 300);
    }),
    3 // Max 3 attempts
  );
}

readUnreliableSensor("THERMO-07")
  .then(data => console.log("Final reading:", data.value.toFixed(1)))
  .catch(error => console.error("All retries failed:", error.message));

Async Generators

Async generators combine generators with async operations - perfect for streaming data:

async function* streamDinoUpdates(dinoIds, intervalMs) {
  for (const id of dinoIds) {
    // Simulate fetching live update for each dinosaur
    await new Promise(res => setTimeout(res, intervalMs));
    const update = await fetchDinosaurData(id);
    yield { timestamp: new Date().toISOString(), dinosaur: update };
  }
}

// Consuming the async generator
async function monitorLive() {
  const generator = streamDinoUpdates([1, 2, 3, 4, 5], 500);

  for await (const update of generator) {
    console.log(`[${update.timestamp}] ${update.dinosaur.name}: health ${update.dinosaur.health}%`);
  }

  console.log("Live monitoring cycle complete.");
}

monitorLive();

Common Mistakes to Avoid

// Mistake 1: Using await without async
function badFunction() {
  const data = await fetchDinosaurData(1); // SyntaxError!
}

// Fix: Mark function as async
async function goodFunction() {
  const data = await fetchDinosaurData(1); // OK
}

// Mistake 2: Sequential awaits for independent operations (slow)
async function slowReport(id) {
  const a = await fetchDinosaurData(id);
  const b = await fetchEnclosureStatus(a.enclosureId); // Only needs enclosureId
  const c = await fetchVetReport(id); // Independent - but waits for b to finish!
  return { a, b, c };
}

// Fix: Parallel where possible
async function fastReport(id) {
  const dino = await fetchDinosaurData(id);
  const [enclosure, vetReport] = await Promise.all([
    fetchEnclosureStatus(dino.enclosureId),
    fetchVetReport(id) // Runs in parallel with enclosure fetch
  ]);
  return { dino, enclosure, vetReport };
}

// Mistake 3: Forgetting to await - fires and forgets
async function badSave(data) {
  saveToDatabase(data); // Not awaited - errors are silently swallowed!
  console.log("Saved!"); // Prints before save completes
}

// Fix: Always await async operations whose result matters
async function goodSave(data) {
  await saveToDatabase(data);
  console.log("Saved!");
}

function saveToDatabase(data) { return new Promise(res => setTimeout(res, 500)); }

Design Patterns with async/await

The async/await syntax opens new possibilities for design patterns in JavaScript. Here are a few useful patterns:

Retry Pattern

async function withRetries(operation, options = {}) {
  const { maxAttempts = 3, delay = 1000, backoffMultiplier = 2 } = options;

  let lastError;

  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      if (attempt > 1) {
        console.log(`Attempt ${attempt}/${maxAttempts}...`);
      }

      return await operation();
    } catch (error) {
      console.error(`Attempt ${attempt} failed: ${error.message}`);
      lastError = error;

      if (attempt < maxAttempts) {
        const waitTime = delay * Math.pow(backoffMultiplier, attempt - 1);
        console.log(`Waiting ${waitTime}ms before the next attempt...`);
        await new Promise(resolve => setTimeout(resolve, waitTime));
      }
    }
  }

  throw new Error(`Operation failed after ${maxAttempts} attempts. Last error: ${lastError.message}`);
}

// Example usage
async function connectToSecuritySystem() {
  return withRetries(
    async () => {
      const connection = await establishSecuritySystemConnection();
      const authentication = await authenticateConnection(connection);
      return await fetchSecurityStatus(connection, authentication);
    },
    {
      maxAttempts: 5,
      delay: 2000,
      backoffMultiplier: 1.5
    }
  );
}

Timeout Pattern

async function withTimeout(operation, timeLimit, message) {
  // Create a Promise that rejects after the time limit
  const timeoutPromise = new Promise((_, reject) => {
    setTimeout(() => {
      reject(new Error(`Time limit exceeded (${timeLimit}ms): ${message}`));
    }, timeLimit);
  });

  // Race between the operation and the timeout
  return Promise.race([operation(), timeoutPromise]);
}

// Example usage
async function safeTemperatureReading(enclosureId) {
  try {
    const temperature = await withTimeout(
      () => readEnclosureTemperature(enclosureId),
      5000,
      `Reading temperature of enclosure #${enclosureId}`
    );

    console.log(`Enclosure #${enclosureId}: ${temperature}ยฐC`);
    return temperature;
  } catch (error) {
    console.error(`Temperature reading error: ${error.message}`);
    return null; // Or we can return a default value
  }
}

Retry with Exponential Backoff

async function withExponentialBackoff(operation, options = {}) {
  const {
    maxAttempts = 5,
    baseWait = 1000,
    maxWait = 30000,
    jitter = true
  } = options;

  let attempt = 0;

  while (true) {
    try {
      return await operation(++attempt);
    } catch (error) {
      if (attempt >= maxAttempts) {
        throw new Error(`Operation failed after ${attempt} attempts: ${error.message}`);
      }

      // Calculate wait time with exponential backoff
      let waitTime = Math.min(
        maxWait,
        baseWait * Math.pow(2, attempt - 1)
      );

      // Add jitter (randomness) to the wait time
      if (jitter) {
        waitTime = waitTime * (0.5 + Math.random() * 0.5);
      }

      console.log(`Attempt ${attempt} failed. Waiting ${Math.round(waitTime)}ms before the next attempt...`);

      await new Promise(resolve => setTimeout(resolve, waitTime));
    }
  }
}

// Example usage
async function synchronizeDataWithCentral() {
  return withExponentialBackoff(
    async (attempt) => {
      console.log(`Sync attempt #${attempt}...`);
      const data = await fetchCurrentData();
      await sendDataToCentral(data);
      return `Synchronization completed: ${data.length} records`;
    },
    {
      maxAttempts: 10,
      baseWait: 2000,
      maxWait: 60000
    }
  );
}

Waterfall Pattern (Cascade Operations)

async function cascadeSearch(query) {
  console.log(`Starting cascade search for: ${query}`);

  // Try the cache first
  try {
    console.log("Searching cache...");
    const cacheResult = await searchCache(query);
    console.log("Found in cache!");
    return {
      source: "cache",
      result: cacheResult
    };
  } catch (error) {
    console.log("Not found in cache, trying local database...");
  }

  // Then try the local database
  try {
    const localResult = await searchLocalDatabase(query);
    console.log("Found in local database!");
    // Update cache
    await updateCache(query, localResult);
    return {
      source: "local_db",
      result: localResult
    };
  } catch (error) {
    console.log("Not found in local database, trying central database...");
  }

  // Finally try the central database
  try {
    const centralResult = await searchCentralDatabase(query);
    console.log("Found in central database!");
    // Update local database and cache
    await updateLocalDatabase(query, centralResult);
    await updateCache(query, centralResult);
    return {
      source: "central_db",
      result: centralResult
    };
  } catch (error) {
    throw new Error(`No results found for query: ${query}`);
  }
}

Summary

The async/await syntax offers an elegant and readable way of working with asynchronous code in JavaScript, built on top of Promises. Here are the main advantages:

  1. Readability - code looks more like synchronous code, making it easier to understand program flow
  2. Error handling - ability to use standard try/catch syntax instead of .catch()
  3. Debugging - easier stack trace tracking and breakpoint setting
  4. Composition - easier to compose complex asynchronous operations

However, keep a few important points in mind:

  1. Async functions always return a Promise - even if you don't use await inside the function
  2. Watch out for sequential execution - using await before each call causes sequential execution, which may not be optimal
  3. Don't forget error handling - always use try/catch or .catch() when calling async functions
  4. Use Promise.all() for parallel execution - when operations are independent and can run in parallel

In Jurassic Park, as in any complex JavaScript application, async/await is an invaluable tool for managing asynchronous operations, such as communicating with security systems, monitoring dinosaurs, or coordinating various park subsystems.

In the next exercise we will focus on error handling strategies in asynchronous code, which is crucial for creating resilient and reliable applications.

Code for this lesson: index.js
// Closure Counter - Closures
console.log("CLOSURE - DINOSAUR COUNTER\n");

// Closure - a function that remembers its environment
function createDinosaurCounter(species) {
  let count = 0; // Private variable

  return {
    increment: function() {
      count++;
      console.log(`${species} count: ${count}`);
      return count;
    },

    decrement: function() {
      if (count > 0) {
        count--;
        console.log(`${species} count: ${count}`);
      } else {
        console.log(`${species} count is already 0!`);
      }
      return count;
    },

    getCount: function() {
      return count;
    },

    reset: function() {
      count = 0;
      console.log(`${species} counter reset`);
    }
  };
}

// Creating counters for different species
console.log("=== CREATING COUNTERS ===\n");

const trexCounter = createDinosaurCounter('T-Rex');
const velociraptorCounter = createDinosaurCounter('Velociraptor');

console.log("T-Rex:");
trexCounter.increment(); // 1
trexCounter.increment(); // 2
trexCounter.increment(); // 3

console.log("\nVelociraptor:");
velociraptorCounter.increment(); // 1
velociraptorCounter.increment(); // 2

console.log("\nT-Rex again:");
trexCounter.increment(); // 4

console.log(`\n=== COUNTER STATE ===`);
console.log(`T-Rex: ${trexCounter.getCount()}`);
console.log(`Velociraptor: ${velociraptorCounter.getCount()}`);

console.log("\n=== DECREMENT ===\n");
trexCounter.decrement(); // 3
velociraptorCounter.decrement(); // 1
velociraptorCounter.decrement(); // 0
velociraptorCounter.decrement(); // Attempt to go below 0

console.log("\n=== RESET ===\n");
trexCounter.reset();
console.log(`T-Rex after reset: ${trexCounter.getCount()}`);

// count is inaccessible from outside!
// console.log(count); // ERROR! count is private

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What does the await keyword do?

  2. 2. What does a function marked with the async keyword automatically return?

These are 2 of 4 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Write an async function that uses await to sequentially check three dinosaur sensors and display the results.

  • Horizontal ordering

    Arrange the elements of parallel Promise execution:

  1. Questionasync/await
  2. QuestionAsync Function
  3. Coding taskPractice: async/await
  4. QuestionPromise.allSettled()
  5. QuestionPromise.race
  6. Put in orderPromise.all Syntax

Useful articles