Lecture JS - Asyncronous Programming - Part 3
Lecture JS - Asyncronous Programming - Part 3
if (success) {
resolve("Operation successful!");
} else {
reject("Operation failed.");
}
});
myPromise
.then(result => {
console.log(result); // Logs "Operation successful!"
})
.catch(error => {
console.log(error); // Logs "Operation failed." if the promise is rejected
});
Chaining Promises:
You can chain multiple .then() calls to handle sequences of asynchronous tasks. Each .then() gets the resolved value from the previous
promise.
myPromise
.then(result => {
console.log(result); // "Operation successful!"
return "Next step";
})
.then(nextResult => {
console.log(nextResult); // "Next step"
})
.catch(error => {
console.log(error); // Handles any error that might occur
});
Promise.all:
If you have multiple promises and want to wait for all of them to be fulfilled or rejected, you can use Promise.all. It returns a new promise
that resolves when all the provided promises have resolved, or rejects if any of the promises reject.
Promise.race([promise1, promise2])
.then(result => {
console.log(result); // "Second" because promise2 resolves first
});
async / await
async / await:
async and await are syntax sugar that work with Promises and allow you to write asynchronous
code in a more synchronous-like fashion.
async: Used to declare an asynchronous function that always returns a promise.
await: Used inside an async function to pause execution until the promise is resolved or
rejected.
function delay(ms) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(`Waited for ${ms} milliseconds`);
}, ms);
});
}
console.log('All done!');
}
doWork();
delay(1000) returns a Promise.
await pauses doWork() until the Promise resolves.
The code runs top-to-bottom like synchronous code, even though it’s asynchronous under the
hood.
fetch
What it is: fetch is a function in modern JavaScript (part of the Fetch API) used to make
network requests — usually HTTP requests to APIs.
Purpose: It fetches resources (like JSON data from a server) and returns a Promise that resolves
to the response.
How it works: When you call fetch(url), it returns a Promise that resolves when the HTTP
response is received. Then you typically call .json() or .text() on the response to parse it.
Common HTTP Request Methods
Method Description
Retrieves data from a server. Should not change
GET
anything on the server.
Sends data to a server to create a resource. Often
POST
used for form submissions.
Sends data to update or create a resource. Usually
PUT
replaces the entire resource.
Sends partial updates to a resource. More precise
PATCH
than PUT.
DELETE Deletes the specified resource from the server.
Same as GET but only returns headers (no response
HEAD
body). Used for metadata.
Returns the HTTP methods supported by a server
OPTIONS
(used in CORS preflight checks).
Establishes a tunnel to the server (used mostly for
CONNECT
HTTPS).
Echoes the received request (used for debugging).
TRACE
Rarely used in practice.
Use fetch to get data
<Button class="reqBtn">Click Me To Request For Data</Button>
<script>
const reqBtn = document.querySelector('.reqBtn');
const url = 'https://jsonplaceholder.typicode.com/users';
//const userData = () => {
// fetch(url)
// .then(res => res.json())
// .then(data => console.log(data));
//}
//reqBtn.addEventListener('click', () => {
// userData();
//})
//asyn example
const userData = async () => {
const req = await fetch(url);
const data = await req.json();
console.log(data);
}
reqBtn.addEventListener('click', () => {
userData();
})
</script>
Create a Promise Using fetch
function fetchData(url) {
return new Promise((resolve, reject) => {
fetch(url)
.then((response) => {
if (!response.ok) {
reject(`HTTP error! status: ${response.status}`);
} else {
return response.json();
}
})
.then((data) => resolve(data))
.catch((error) => reject(`Fetch failed: ${error}`));
});
}
// Usage
fetchData("https://jsonplaceholder.typicode.com/posts/1")
.then((data) => {
console.log(" Data received:", data);
})
.catch((error) => {
console.error(" Error occurred:", error);
});
Use fetch to post data
<button onclick="sendPost()">Send POST</button>
<script>
function sendPost() {
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: 'Hello World',
body: 'This is a test post.',
userId: 1
}),
})
.then(response => response.json())
.then(data => {
console.log('POST Success:', data);
alert('POST response ID: ' + data.id);
})
.catch(error => {
console.error('Error:', error);
});
}
</script>
Summary
Promises provide a way to handle asynchronous operations.
They have three states: pending, fulfilled, and rejected.
You can chain .then() to handle fulfilled promises, and .catch() for errors.
Use async and await to simplify working with promises, making asynchronous code easier to
read.