James Williams
console.log('First');
console.log('Second');
console.log('Third');
// Output: First, Second, Third
console.log('First');
setTimeout(() => console.log('Second'), 1000);
console.log('Third');
// Output: First, Third, Second (after 1s)
function fetchData(callback) {
setTimeout(() => {
const data = {name: 'John', age: 30};
callback(data);
}, 1000);
}
fetchData((result) => {
console.log(result);
});
getData(function(a) {
getMoreData(a, function(b) {
getMoreData(b, function(c) {
// Nested callbacks...
});
});
});
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
const success = true;
if (success) {
resolve({data: 'Success!'});
} else {
reject(new Error('Failed'));
}
}, 1000);
});
promise
.then(result => console.log(result))
.catch(error => console.error(error));
// Promise approach
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
// async/await approach
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
// GET request
fetch('https://api.github.com/users/github')
.then(response => response.json())
.then(data => console.log(data));
// POST request
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({name: 'John', age: 30})
})
.then(response => response.json())
.then(data => console.log(data));
Build a weather application using the OpenWeather API
async function fetchUserData(userId) {
try {
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Failed to fetch user:', error);
throw error; // Re-throw if needed
} finally {
console.log('Fetch attempt completed');
}
}
Create a todo app using JSONPlaceholder API
async function fetchMultiple() {
try {
const [users, posts, comments] = await Promise.all([
fetch('/api/users').then(r => r.json()),
fetch('/api/posts').then(r => r.json()),
fetch('/api/comments').then(r => r.json())
]);
return {users, posts, comments};
} catch (error) {
console.error('One of the requests failed:', error);
}
}
const fastest = await Promise.race([
fetch('https://api1.example.com'),
fetch('https://api2.example.com')
]);
Preparation: Install Python 3.11+ and ensure pip is working.
Contact: JWilliams@Staff.newman.ac.uk
Office Hours: By appointment
Resources: MDN Fetch API, JavaScript.info
Thank you for your attention!