lec_6_7_part_1
lec_6_7_part_1
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
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.."]
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
}