• in
InterCourses
CoursesBlogs
0
← Introduction to JavaScript
○What is JavaScript?○Your First JavaScript Code○Data Types○Type Checking
○Declaring Variables○let and const in Practice○Operators○Type Conversion
○Conditionals○Switch Statement○For Loops○While Loop○Break and Continue
○Defining Functions○Arrow Functions○Scope○Closures○Project - Calculator○Function Expressions
○Arrays○Array Mutation Methods○Array Search and Slice○Array Iteration Methods○Multidimensional Arrays○Destructuring○Array Reverse and Sort○Array Fill○Array Find and Includes○Array Flat and FlatMap○Array Reduce, Some, and Every
○Objects○Object Methods and Destructuring○JSON○Math and Date○Date Basics
○02 Template Literals○String Methods○Regular Expressions
○Higher-Order Functions○Callbacks○map, filter, and reduce○Recursion○Project - Data Transform Pipeline
○OOP Introduction○Classes○Inheritance○Encapsulation
○Asynchronous JavaScript●Promises and Async Await○Async API Simulation

Promises and Async Await

Promises and async/await

A Promise represents a value that may be available now, later, or never.

Creating a Promise

javascript
const promise = new Promise((resolve, reject) => {
    const success = true;
    if (success) resolve("Done");
    else reject(new Error("Failed"));
});

Consuming with .then/.catch

javascript
promise
  .then(result => console.log(result))
  .catch(error => console.error(error.message));

async and await

async functions always return a Promise. await pauses inside async functions until a Promise settles:

javascript
async function run() {
    try {
        const result = await promise;
        console.log(result);
    } catch (err) {
        console.error(err.message);
    }
}

Your Task

  1. Write a function delay(ms, value) that returns a Promise resolving with value after ms milliseconds.
  2. Write an async function loadMessage() that:
    • awaits delay(10, "Hello Async")
    • returns the message in uppercase.
  3. Write an async function safeDivide(a, b) that:
    • returns a rejected Promise with Error("Division by zero") when b === 0
    • otherwise resolves to a / b
  4. Run loadMessage() and safeDivide(10, 2), then display in #output: "HELLO ASYNC | 10/2 = 5".
Hint 1
1 / 3
HINT 1

A Promise has 3 states: pending, fulfilled, rejected.

Loading editor…
READY
intercourses
javascript