1. Synchronous JavaScript
Synchronous means code executes one line at a time, in order. The next line waits until the current line finishes.
Example:
console.log("First");
console.log("Second");
console.log("Third");
Output :
First
Second
Third
Explanation:
- First line executes.
- Then the second line executes.
- Finally, the third line executes. Each statement runs in sequence.
2. Asynchronous JavaScript
Asynchronous means some operations can start and finish later, allowing other code to run while waiting.
console.log("First");
setTimeout(() => {
console.log("Second");
}, 2000);
console.log("Third");
Output :
First
Third
Second
Explanation:
- "First" prints immediately.
- setTimeout() schedules the callback to run after at least 2 seconds.
- "Third" prints without waiting for the timer.
- "Second" prints when the timer callback run
3. What is a Promise?
A Promise is a JavaScript object that represents the eventual success or failure of an asynchronous operation.
A Promise has three states:
- Pending: The operation has not finished.
- Fulfilled: The operation succeeded.
- Rejected: The operation failed.
Example:
let myPromise = new Promise((resolve, reject) => {
resolve("Task completed!");
});
myPromise.then((result) => {
console.log(result);
});
Output :
Task completed!
Explanation:
- new Promise() creates a Promise.
- resolve() indicates success.
- .then() handles the successful result.
- reject() is used to indicate failure.
Here's an example of a rejected Promise:
let myPromise = new Promise((resolve, reject) => {
reject("Something went wrong");
});
myPromise.catch((error) => {
console.log(error);
});
Output :
Something went wrong
Top comments (0)