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:
- Use `setTimeout` to log "Hello" after 3 seconds.
- Write the callback as an arrow function.
Solution
setTimeout(() => {
console.log("Hello");
}, 3000);
Exercise 2
SetInterval
Create a counter:
- Use `setInterval` to log an increasing number every second (1, 2, 3...).
- 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:
- Create a `Promise` that checks a `success` variable.
- If `true`, resolve with "Success".
- If `false`, reject with "Failure".
- 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:
- You have JSON text: `'{"name": "Ali", "age": 25}'`.
- Convert it to a JavaScript object using `JSON.parse()`.
- 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:
- You have `product = { id: 1, title: "Phone" }`.
- Convert it to a JSON string using `JSON.stringify()`.
- 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:
- Use `fetch` to get data from `https://api.example.com/data`.
- Convert the response to JSON.
- 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:
- Create an async function `async function getData()`.
- Use `await` for the fetch and JSON conversion.
- 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:
- Use `fetch` to send a `POST` request to `https://api.example.com/users`.
- Set the `method` and `headers` (Content-Type: application/json).
- 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:
- You have two promises `p1` and `p2`.
- Use `Promise.all([p1, p2])` to wait for both.
- 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:
- Save the value "dark" under the key "theme" using `localStorage.setItem`.
- Read the saved value using `localStorage.getItem` and log it.
Solution
localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme");
console.log(theme); // dark