0% found this document useful (0 votes)
0 views24 pages

Lecture JS - Asyncronous Programming - Part 3

Promises in JavaScript represent the completion or failure of asynchronous operations, with three states: pending, fulfilled, and rejected. They allow for chaining with .then() for success and .catch() for errors, and can be simplified using async/await syntax. The document also covers the fetch API for making network requests and how to handle data retrieval and posting using promises.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views24 pages

Lecture JS - Asyncronous Programming - Part 3

Promises in JavaScript represent the completion or failure of asynchronous operations, with three states: pending, fulfilled, and rejected. They allow for chaining with .then() for success and .catch() for errors, and can be simplified using async/await syntax. The document also covers the fetch API for making network requests and how to handle data retrieval and posting using promises.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Promise

In JavaScript, a Promise is an object that represents the eventual completion or failure of an


asynchronous operation. It allows you to work with asynchronous code in a more synchronous-
like manner, making it easier to manage than callbacks.
A Promise has three possible states:
1. Pending: The initial state, before the promise is settled (either fulfilled or rejected).
2. Fulfilled: The operation completed successfully.
3. Rejected: The operation failed.
let promise = new Promise((resolve, reject) => {
// asynchronous code here
});

resolve(value): This function is called when the asynchronous operation is successful. It


transitions the promise to the fulfilled state.
reject(reason): This function is called when the asynchronous operation fails. It transitions the
promise to the rejected state.
let myPromise = new Promise((resolve, reject) => {
let success = true;

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.

let promise1 = Promise.resolve(3);


let promise2 = Promise.resolve(4);
let promise3 = new Promise((resolve, reject) => setTimeout(resolve, 100, 5));

Promise.all([promise1, promise2, promise3])


.then(values => {
console.log(values); // [3, 4, 5]
})
.catch(error => {
console.log(error); // If any promise fails, this will be triggered
});
Promise.race:
Promise.race returns a promise that resolves or rejects as soon as one of the input promises
resolves or rejects.

let promise1 = new Promise((resolve, reject) => setTimeout(resolve, 500, 'First'));


let promise2 = new Promise((resolve, reject) => setTimeout(resolve, 100, 'Second'));

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);
});
}

This delay function simulates an asynchronous operation using setTimeout.


async function doWork() {
console.log('Starting...');

const result1 = await delay(1000); // Waits 1 second


console.log(result1);

const result2 = await delay(2000); // Waits 2 more seconds


console.log(result2);

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.

You might also like