function task1() {
// Task 1 execution
}
function task2() {
// Task 2 execution
}
task1();
task2(); // Task 2 starts only after Task 1 finishes
function task1() {
// Task 1 execution
}
function task2() {
// Task 2 execution
}
setTimeout(task1, 1000); // Task 1 is delayed
task2(); // Task 2 can run before Task 1 completes
// Parallel execution with multiple threads
parallelize(task1, task2);
A Promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation.
const promise = new Promise((resolve, reject) => {
// asynchronous operation
});
Promises have three states:
let promise = new Promise((resolve, reject) => {
// initially pending
});
The resolve()
function signals the success of the asynchronous operation.
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Success!"), 1000);
});
promise.then(result => console.log(result)); // "Success!" after 1 second
The reject()
function is used to signal failure in the operation.
const promise = new Promise((resolve, reject) => {
setTimeout(() => reject(new Error("Failure!")), 1000);
});
promise.catch(error => console.error(error)); // Error: Failure!
then
, catch
, finally
then()
: Used to handle the success case.catch()
: Used to handle errors or rejection.finally()
: Runs regardless of the outcome.promise
.then(result => console.log(result))
.catch(error => console.error(error))
.finally(() => console.log("Operation complete"));
Promises can be chained to handle sequences of asynchronous operations.
fetchData()
.then(data => processData(data))
.then(result => displayResult(result))
.catch(error => handleError(error));
async
/await
simplifies working with promises by allowing you to write asynchronous code that looks synchronous.
async function fetchData() {
try {
let data = await fetch('https://api.example.com/data');
console.log(data);
} catch (error) {
console.error(error);
}
}
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
}
async
Worksasync
, it automatically returns a Promise.async
keyword allows the use of the await
keyword within that function.async function myAsyncFunction() {
return "Hello, Async!";
}
myAsyncFunction().then(result => console.log(result)); // "Hello, Async!"
async
, the above function would just return a regular value, not a Promise.await
Worksawait
keyword is used inside async
functions to pause the execution of the function until the Promise is resolved.async function fetchData() {
let response = await fetch('https://api.example.com/data');
let data = await response.json();
console.log(data);
}
await
await
pauses the function execution until the promise is settled (either resolved or rejected).await
pauses the async function, it does not block the execution of other code outside the function.async function demo() {
console.log("Start");
let result = await someAsyncTask();
console.log(result);
}
console.log("Code after async call"); // This will run immediately
.catch()
to handle errors in Promises, async/await
allows you to handle errors with try-catch blocks.async function fetchData() {
try {
let response = await fetch('https://api.invalid-url.com');
let data = await response.json();
console.log(data);
} catch (error) {
console.error("An error occurred:", error);
}
}
async function loadData() {
let promise1 = fetch('https://api.example.com/data1');
let promise2 = fetch('https://api.example.com/data2');
let [data1, data2] = await Promise.all([promise1, promise2]);
console.log(data1, data2);
}
Promise.all()
with Async/AwaitPromise.all()
allows you to run multiple asynchronous tasks in parallel and wait for all of them to complete.async function getData() {
let [result1, result2] = await Promise.all([
fetch('https://api.example.com/data1'),
fetch('https://api.example.com/data2')
]);
console.log(result1, result2);
}
try-catch
, making error management more straightforward..then()
and .catch()
for handling asynchronous operations.await
and try-catch
for error handling.Feature | Promises | Async/Await |
---|---|---|
Syntax | More verbose | Cleaner, more readable |
Error Handling | .catch() |
try-catch |
Execution Style | Chain-based | Synchronous-looking |
Performance | Can be parallelized | Can use Promise.all() for parallelism |
Promise.all()
for parallelism when needed.then()
, catch()
, and finally()
offer flexibility.