JS Exam 5: Asynchronous JS and APIs (10 mixed exercises)

JS Exam 5: Async Programming and APIs

Test your ability to handle asynchronous operations, fetch data from servers, and work with JSON.

Exercise 1 SetTimeout

Run code after a delay:

  1. Use `setTimeout` to log "Hello" after 3 seconds.
  2. Write the callback as an arrow function.
Solution
setTimeout(() => {
    console.log("Hello");
}, 3000);
Exercise 2 SetInterval

Create a counter:

  1. Use `setInterval` to log an increasing number every second (1, 2, 3...).
  2. Stop the counter (clearInterval) when it reaches 5.
Solution
let count = 0;
const intervalId = setInterval(() => {
    count++;
    console.log(count);
    if (count === 5) {
        clearInterval(intervalId);
    }
}, 1000);
Exercise 3 Promises

Create a simple promise:

  1. Create a `Promise` that checks a `success` variable.
  2. If `true`, resolve with "Success".
  3. If `false`, reject with "Failure".
  4. Use `.then()` and `.catch()` to handle the result.
Solution
const myPromise = new Promise((resolve, reject) => {
    const success = true;
    if (success) {
        resolve("Success");
    } else {
        reject("Failure");
    }
});

myPromise
    .then(msg => console.log(msg))
    .catch(err => console.error(err));
Exercise 4 JSON Parsing

Work with JSON data:

  1. You have JSON text: `'{"name": "Ali", "age": 25}'`.
  2. Convert it to a JavaScript object using `JSON.parse()`.
  3. Log the `name` property.
Solution
const jsonString = '{"name": "Ali", "age": 25}';
const user = JSON.parse(jsonString);

console.log(user.name); // Ali
Exercise 5 JSON Stringify

Convert an object to JSON:

  1. You have `product = { id: 1, title: "Phone" }`.
  2. Convert it to a JSON string using `JSON.stringify()`.
  3. Log the result.
Solution
const product = { id: 1, title: "Phone" };
const jsonString = JSON.stringify(product);

console.log(jsonString); // '{"id":1,"title":"Phone"}'
Exercise 6 Fetch API (GET)

Fetch data from a placeholder URL:

  1. Use `fetch` to get data from `https://api.example.com/data`.
  2. Convert the response to JSON.
  3. Log the data to the console.
Solution
fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error(error));
Exercise 7 Async/Await

Rewrite the Fetch code using Async/Await:

  1. Create an async function `async function getData()`.
  2. Use `await` for the fetch and JSON conversion.
  3. Wrap the code in `try...catch` to handle errors.
Solution
async function getData() {
    try {
        const response = await fetch('https://api.example.com/data');
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error(error);
    }
}

getData();
Exercise 8 Fetch API (POST)

Send data to a server:

  1. Use `fetch` to send a `POST` request to `https://api.example.com/users`.
  2. Set the `method` and `headers` (Content-Type: application/json).
  3. Send the body as JSON: `{ name: "Ali" }`.
Solution
fetch('https://api.example.com/users', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({ name: "Ali" })
})
.then(res => res.json())
.then(data => console.log(data));
Exercise 9 Promise.all

Run multiple promises in parallel:

  1. You have two promises `p1` and `p2`.
  2. Use `Promise.all([p1, p2])` to wait for both.
  3. Log the results when done.
Solution
const p1 = Promise.resolve("First");
const p2 = Promise.resolve("Second");

Promise.all([p1, p2]).then(results => {
    console.log(results); // ["First", "Second"]
});
Exercise 10 Local Storage

Store data in the browser:

  1. Save the value "dark" under the key "theme" using `localStorage.setItem`.
  2. Read the saved value using `localStorage.getItem` and log it.
Solution
localStorage.setItem("theme", "dark");

const theme = localStorage.getItem("theme");
console.log(theme); // dark
Smart Editor

Write code and see the result instantly

Try it free