0% found this document useful (0 votes)
2 views

lec_6_7_part_1

The document explains JavaScript Promises, which are used to handle asynchronous operations by representing a future value. It details the syntax for creating and consuming promises, their states (pending, fulfilled, rejected), and provides examples of using promises and the async/await syntax for cleaner asynchronous code. Additionally, it covers error handling in async functions using try/catch blocks.

Uploaded by

r.soliman3526
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

lec_6_7_part_1

The document explains JavaScript Promises, which are used to handle asynchronous operations by representing a future value. It details the syntax for creating and consuming promises, their states (pending, fulfilled, rejected), and provides examples of using promises and the async/await syntax for cleaner asynchronous code. Additionally, it covers error handling in async functions using try/catch blocks.

Uploaded by

r.soliman3526
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

1

Lec 6: Asynchronous JavaScript & Promise


Asynchronous JavaScript (you will find in summary 5)
JavaScript Promise (slide 7)
What is a Promise?
- A promise in JavaScript is like a container for a future value. It is a
way of saying, “I don’t have this value right now, but I will have it
later.”
- A Promise contains both the producing code and calls to the
consuming code
- In the same way, a promise lets you keep working with your code
while waiting for something else to finish, like loading data from a
server. When the data is ready, the promise will deliver it
Syntax
let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)
myResolve(); // when successful
myReject(); // when error
});
// "Consuming Code" (Must wait for a fulfilled Promise)
myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
2

Parameters
• The promise constructor takes only one argument which is a
callback function
• The callback function takes two arguments, resolve and reject
• Perform operations inside the callback function and if
everything went well then call resolve.
• If desired operations do not go well then call reject.
How Does a Promise Work?
A promise can be in one of three states:
• Pending: The promise is waiting for something to finish. For
example, waiting for data to load from a website.
• Fulfilled: The promise has been completed successfully. The data
you were waiting for is now available.
• Rejected: The promise has failed. Maybe there was a problem, like
the server not responding.
When the producing code obtains the result, it should call one of the
two callbacks:
3

Example
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Promise Object</h1>
<h2>The then() Method</h2>
<p id="demo"></p>
<script>
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
let myPromise = new Promise(function(myResolve, myReject) {
let x = 0;
// some code (try to change x to 5)
if (x == 0) {
myResolve("OK");
} else {
myReject("Error");
}
});
myPromise.then(
function(value) {myDisplayer(value);},
function(error) {myDisplayer(error);}
);
</script>
</body>
</html>

Output:
JavaScript Promise Object
The then() Method
OK
4

Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Callbacks</h2>
<p id="demo"></p>
<script>
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
function getFile(myCallback) {
let req = new XMLHttpRequest();
req.onload = function() {
if (req.status == 200) {
myCallback(this.responseText);
} else {
myCallback("Error: " + req.status);
}
}
req.open('GET', "mycar.html");
req.send();
}
getFile(myDisplayer);
</script>
</body>
</html>
 Output ((e.g., mycar.html contains the text "My car is a Tesla")):
JavaScript Callbacks
My car is a Tesla
5

Example using Promise


<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Promise Object</h1>
<h2>The then() Metod</h2>
<p id="demo"></p>
<script>
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
let myPromise = new Promise(function(myResolve, myReject) {
let req = new XMLHttpRequest();
req.open('GET', "mycar.html");
req.onload = function() {
if (req.status == 200) {
myResolve(req.response);
} else {
myReject("File not Found");
}};
req.send();
});
myPromise.then(
function(value) {myDisplayer(value);},
function(error) {myDisplayer(error);}
);
</script>
</body>
</html>

 Output ((e.g., mycar.html contains the text "My car is a Tesla")):


JavaScript Callbacks
The then() Metod
My car is a Tesla
6

Lec 7 part 1: Async and Await in JavaScript


Async and Await
Async and Await in JavaScript is used to simplify handling asynchronous
operations using promises.

Async Function
Asyn function allows us to write promise-based code as if it were synchronous.
This ensures that the execution thread is not blocked.

Promise Handling:
Async functions always return a promise. If a value is returned that is not a
promise, JavaScript automatically wraps it in a resolved promise.

Async Syntax
async function myFunction() {
return "Hello";
}
Example
const getData = async () => {
let data = "Hello World";
return data;
}
getData().then(data => console.log(data));

Await Keyword
await keyword is used to wait for a promise to resolve. It can only be used within
an async block.
Await makes the code wait until the promise returns a result, allowing for cleaner
and more manageable asynchronous code.

Syntax
let value = await promise;
7

Example
const getData = async () => {
let y = await "Hello World";
console.log(y);
}
console.log(1);
getData();
console.log(2);

Output:
1
2
Hello World

Async/Await Example
function asynchronous_operational_method() {
let first_promise =
new Promise((resolve, reject) => resolve("Hello"));
let second_promise =
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(" java Script..");
}, 1000);
});
let combined_promise =
Promise.all([first_promise, second_promise]);
return combined_promise;
}
async function display() {
let data = await asynchronous_operational_method();
console.log(data);
}
display();
8

 Output:
["Hello", " java Script.."]

How to Handle Errors in Async/Await


To handle an error that might occur from the async/await syntax, you can use the
try/catch block to catch any rejection from your promise.

Example
async function runProcess() {
try {
const response = await
fetch('https://jsonplaceholder.typicode.com/todos/1');
const json = await response.json();
console.log(json);
} catch (error) {
console.log(error);
}
}
runProcess();

 Output:
{
userId: 1,
id: 1,
title: "delectus aut autem",
completed: false
}

You might also like