javascript is default asynchronous
normally syncchronous means one by line execution -> it will stop till before lin execution
aynchrnous also line by line-> if line is aynchrnous -> it will not stop if before line is aynchrnous-> it will continue to next line
when asyncrhonos line executed -> that wil stop present execution
Certainly! Here's an example of asynchronous code in JavaScript using the setTimeout
function:
function:
javascriptconsole.log("First");
setTimeout(() => {
console.log("Third");
}, 2000);
console.log("Second");
IIn the above code, we have three console.log
statements. The first and second console.log
statements are executed synchronously, so they will be logged immediately. However, the third console.log
statement is placed inside the setTimeout
function, which schedules it to be executed asynchronously after a delay of 2 seconds.
When you run this code, the output will be:
sqlFirst
Second
Third (logged after 2 seconds)
As you can see, the third console.log
statement is executed asynchronously after the delay, allowing the code execution to continue without waiting for it. This demonstrates the asynchronous nature of JavaScript.
In the above code, the fetchData
function simulates an asynchronous operation that fetches data after a delay of 2 seconds. It accepts a callback function processData
as an argument and invokes it with the fetched data. The processData
function processes the data.
promise in javascript
promise is a object -> it has resolve and reject -> if it is success it goes to resolve
if reject -> it will calls catch
A Promise is an object in JavaScript that represents the eventual completion or failure of an asynchronous operation and its resulting value. It provides a way to handle asynchronous operations in a more organized and manageable manner.
A Promise has three states:
- Pending: The initial state. The Promise is still in progress, and the final value is not available yet.
- Fulfilled: The Promise has resolved successfully. The operation completed, and the Promise holds the resulting value.
- Rejected: The Promise encountered an error or failure during its execution.
Here's a basic example of creating and using a Promise:
s
const myPromise = new Promise((resolve, reject) => {
// Asynchronous operation
setTimeout(() => {
const randomNumber = Math.random();
if (randomNumber > 0.5) {
resolve(randomNumber);
} else {
reject("Error: Random number is too small");
}
}, 2000);
});
myPromise
.then(result => {
console.log("Promise fulfilled with result:", result);
})
.catch(error => {
console.log("Promise rejected with error:", error);
});
s
In the example above, we create a Promise using the new Promise()
constructor. Inside the Promise, we perform an asynchronous operation using setTimeout
to generate a random number. If the generated number is greater than 0.5, the Promise is resolved with the number; otherwise, it is rejected with an error message.
To handle the result of the Promise, we use the .then()
method, which takes a callback function to execute when the Promise is fulfilled. If the Promise is rejected, we can handle the error using the .catch()
method, which takes a callback function for error handling.
Promises allow you to chain multiple asynchronous operations together using .then()
and handle errors with .catch()
. They provide a more structured and readable way to handle asynchronous code compared to using callbacks directly.
- Using Promises:
- In this example, the
fetchData
function returns a Promise that resolves with the fetched data. TheprocessData
function is passed as a callback to thethen
method, which executes it when the Promise is resolved. If an error occurs, it is caught using thecatch
method.
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = "Async data";
resolve(data);
}, 2000);
});
}
function processData(data) {
console.log("Processing data:", data);
}
fetchData()
.then(processData)
.catch(error => {
console.error("Error:", error);
});
console.log("This log statement is executed synchronously.");
s
s
- Using async/await:
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = "Async data";
resolve(data);
}, 2000);
});
}
async function processData() {
try {
const data = await fetchData();
console.log("Processing data:", data);
} catch (error) {
console.error("Error:", error);
}
}
processData();
console.log("This log statement is executed synchronously.");
sIn this example, the fetchData
function returns a Promise. The processData
function is marked as async
and uses the await
keyword to wait for the Promise to resolve before continuing execution. Any errors are caught using a try/catch
block.
In all three examples, the log statement outside the asynchronous code block is executed synchronously, demonstrating that JavaScript allows non-blocking execution of asynchronous operations.
No comments:
Post a Comment