console.log('Start');
console.log('Middle');
console.log('End');
Output:
Start
Middle
End
In this case, the execution is in order.
console.log('Start');
setTimeout(() => {
console.log('Middle');
}, 1000);
console.log('End');
Output:
Start
End
Middle
The setTimeout
function runs asynchronously, allowing the code to continue executing while it waits.
let promise = new Promise((resolve, reject) => {
let success = true; // Simulating a condition
if (success) {
resolve('Task completed successfully!');
} else {
reject('Task failed.');
}
});
.then()
is used to handle the successful completion of a promise. It accepts a callback function that gets executed when the promise is resolved.promise.then((message) => {
console.log(message); // Output: Task completed successfully!
});
.catch()
is used to handle errors or rejections in a promise. It accepts a callback function that gets executed when the promise is rejected.promise.catch((error) => {
console.log(error); // Output: Task failed.
});
fetch()
method is used to make network requests and returns a promise that resolves to the response object. This can be used to make API calls to retrieve or send data.fetch(url)
.then(response => response.json()) // Converting the response to JSON
.then(data => console.log(data)) // Handling the data
.catch(error => console.error('Error:', error)); // Handling errors
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log('Error:', error));
async/await
provides a way to work with asynchronous code in a more synchronous-looking manner, making the code easier to read and understand.async function fetchData() {
try {
let response = await fetch('https://api.example.com/data');
let data = await response.json();
console.log(data);
} catch (error) {
console.log('Error:', error);
}
}
fetchData();
Explanation:
fetchData()
is an asynchronous function that uses await
to wait for the fetch
call to complete.try
block is used to handle successful data retrieval, and the catch
block catches any errors that occur during the process.async/await
when you need to handle multiple asynchronous operations sequentially..then()
and .catch()
.