INFO 253A: Front-end Web Architecture
Kay Ashaolu
this
. function longTask() {
// Simulate a long task
for (let i = 0; i < 1e9; i++) {}
}
console.log('Start');
longTask();
console.log('End');
setTimeout
, setInterval
)XMLHttpRequest
, Fetch API) doFirstTask((result1) => {
doSecondTask(result1, (result2) => {
doThirdTask(result2, (result3) => {
// Continue nesting...
});
});
});
const promise = new Promise((resolve, reject) => {
// Asynchronous operation
if (success) {
resolve(result);
} else {
reject(error);
}
});
promise
.then((result) => {
// Handle success
})
.catch((error) => {
// Handle error
});
getUser()
.then((user) => getProfile(user.id))
.then((profile) => getPosts(profile.id))
.then((posts) => console.log(posts))
.catch((error) => console.error(error));
fetch('https://api.example.com/data')
.then((response) => response.json())
.then((data) => console.log(data));
Promise.all()
Promise.all()
waits for multiple promises to resolve. Promise.all([fetchData1(), fetchData2(), fetchData3()])
.then((results) => {
// results is an array of resolved values
console.log(results);
})
.catch((error) => console.error(error));
async function loadData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
// Handle the data
console.log(data);
})
.catch(error => {
// Handle errors
console.error('Error:', error);
});
fetch()
initiates a network request to the provided URL.then()
processes the response, parsing it as JSON.then()
handles the parsed data.catch()
handles any errors that occur during the fetch or processingfetch('movies.json')
.then(response => response.json())
.then(data => {
// Use the data
console.log(data);
});
response.json()
to parse JSON responsesfetch('https://api.example.com/data', {
method: 'POST', // HTTP method
headers: {
'Content-Type': 'application/json', // Specifies the media type
'Authorization': 'Bearer abc123' // Example of an auth token
},
body: JSON.stringify({ title: 'New Post', body: 'This is the content.' }) // Data to send
})
.then(response => response.json())
.then(data => {
// Handle the response
console.log(data);
});
method
: Specifies the HTTP method (GET, POST, PUT, DELETE)headers
: An object containing any custom headers you want to addbody
: The data to send with the request (for POST, PUT)fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
// Response status is not in the range 200-299
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json();
})
.then(data => {
// Handle data
console.log(data);
})
.catch(error => {
// Handle errors
console.error('Fetch error:', error);
});
response.ok
to determine if the request was successful.catch()
to handle any errors that occurasync function fetchData() {
// Function declared with 'async' keyword
const response = await fetch('https://api.example.com/data');
// 'await' pauses the function until the promise resolves
const data = await response.json();
// Use the data
console.log(data);
}
fetchData(); // Call the async function
await
must be declared with async
await
can only be used inside async
functionsawait
keyword makes JavaScript wait until the promise settlestry...catch
blocks to handle errors in async
functionsasync function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
// Throw an error if response status is not OK
throw new Error('HTTP error! status: ' + response.status);
}
const data = await response.json();
// Use the data
console.log(data);
} catch (error) {
// Handle any errors
console.error('Error:', error);
}
}
try
block contains code that may throw an errorcatch
block handles any errors that occur in the try
blockasync function getRandomUser() {
try {
const response = await fetch('https://randomuser.me/api/');
const data = await response.json();
// Extract user data
const user = data.results[0];
displayUser(user);
} catch (error) {
console.error('Error fetching user:', error);
}
}
function displayUser(user) {
// Update the DOM elements with user information
document.getElementById('user-name').textContent = `${user.name.first} ${user.name.last}`;
document.getElementById('user-email').textContent = user.email;
document.getElementById('user-picture').src = user.picture.large;
}
?_limit=5
) to limit resultsasync function getTodos() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos?_limit=5');
const todos = await response.json();
// Display todos in the DOM
todos.forEach(todo => {
// Create DOM elements and append to the list
});
} catch (error) {
console.error('Error fetching todos:', error);
}
}
?_limit=5
) to limit resultsasync function addTodo() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
title: 'New Todo',
completed: false
})
});
const newTodo = await response.json();
// Update the DOM with the new todo
} catch (error) {
console.error('Error adding todo:', error);
}
}
?_limit=5
) to limit resultsasync function updateTodo(id, completed) {
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ completed })
});
const updatedTodo = await response.json();
// Reflect changes in the DOM
} catch (error) {
console.error('Error updating todo:', error);
}
}
async function deleteTodo(id) {
try {
await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`, {
method: 'DELETE'
});
// Remove todo from the DOM
} catch (error) {
console.error('Error deleting todo:', error);
}
}
try...catch
blocks in async functionsresponse.ok
and handle HTTP errors