Asynchronus I/O
Learn about asynchronus I/O
Asynchronous I/O
What is asynchronous I/O?
Asynchronous I/O allows your program to continue running while waiting for operations like loading files or fetching from APIs to complete, instead of stopping and waiting for them to finish.
Benefits of asynchronous I/O?
- Program doesn’t freeze while waiting for data
- Handle multiple requests simultaneously
- Improve application responsiveness
- Better performance for network requests
- Essential for modern web applications
// Modern async/await approach
async function loadGameState() {
try {
// Simulate fetching level data
const levelResponse = await fetch('/api/levels/1');
const levelData = await levelResponse.json();
// Simulate fetching player data
const playerResponse = await fetch('/api/player');
const playerData = await playerResponse.json();
// Combine data
const gameState = {
level: levelData,
player: playerData
};
console.log("Game state loaded:", gameState);
return gameState;
} catch (error) {
console.error("Failed to load game state:", error);
}
}
// Call async function
loadGameState();
What does this code do?
- Defines asynchronous function that takes a callback
- Uses
setTimeoutto simulate delayed operation - Continues executing without blocking
- Calls callback when operation completes
- Callback receives the loaded data
- Shows basic asynchronous pattern
Try It Yourself
%%js // CODE_RUNNER: asynchronus-io async function loadGameData() { try { const response = await fetch(‘https://jsonplaceholder.typicode.com/users/1’); const data = await response.json(); console.log(“Loaded: “ + data.name); return data; } catch (error) { console.error(“Failed to load: “ + error); } }
loadGameData();