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

Asynchronous Programming

The document explains asynchronous programming in JavaScript, focusing on callback functions, promises, and the async/await syntax. It highlights how callbacks enable handling multiple tasks simultaneously and how promises facilitate managing asynchronous operations. Examples illustrate the use of callback functions, promises, and the async/await pattern for cleaner asynchronous code management.

Uploaded by

Mohit kumar
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)
6 views

Asynchronous Programming

The document explains asynchronous programming in JavaScript, focusing on callback functions, promises, and the async/await syntax. It highlights how callbacks enable handling multiple tasks simultaneously and how promises facilitate managing asynchronous operations. Examples illustrate the use of callback functions, promises, and the async/await pattern for cleaner asynchronous code management.

Uploaded by

Mohit kumar
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/ 16

ASYNCHRONOUS

PROGRAMMING
Basis of handling request in
background
UNDERSTANDING FUNCTION AS ARGUMENT
In JS it is possible to pass a function as an
argument to another function and this
technique allows a function to call another
function. A function passed as argument is
known as callback function

“A callback function can run after another


function call is completely finished”

JS function are executed in the sequence they are called. Not in the
sequence the are defined.
CALLBACK FUNCTIONS
JS can handle multiple task simultaneously and
callbacks are fundamental aspects of JS as
they allow you to run code after an
asynchronous operation has been completed.

“Callbacks allow you to handle the results of


an asynchronous operation”

Callbacks continue executing code while the


operation is being executed in the
background. Once the operation has
completed, the callback function is called
with the result of the operation.
CALLBACK FUNCTIONS EXAMPLE
function showResult(result) {

document.getElementById(“rdiv").innerHTML
= result;
}
function calculate(num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);
}
calculate(5, 5, showResult);

Here showResult function is callback function which will be


invoke From calculate function.
CALLBACK USING ARROW FUNCTION
function removeNeg(numbers, callback) {
const myArray = [];
for (const x of numbers) {
if (callback(x)) {
myArray.push(x);
}
}
return myArray;
}

const myNumbers = [4, 1, -20, -7, 5, 9, -6];


const posNumbers = removeNeg(myNumbers, (x) => x >= 0);

document.getElementById("demo").innerHTML = posNumbers;
Callback functions are very useful with asynchronous functions
Where One function has to wait for another function.
ASYNCHRONOUS JAVA SCRIPT
In real life computing problems callbacks are
mostly used with asynchronous functions.
Identical example is JS setTimeout() function.

When using the JavaScript


function setTimeout(), you can specify a
callback function to be executed on time-out.

setTimeout(myFunction, 3000);

function myFunction() {

document.getElementById("demo").innerHTM
L = “Asynchronous JS Programming";
}
ASYNCHRONOUS JAVA SCRIPT
Instead of passing the name of a function as
an argument to another function, you can
always pass a whole function instead

setTimeout(function() {
myFunction(“Async
Programming"); }, 3000);

function myFunction(value) {

document.getElementById("demo").innerHTM
L = value;
}
WAITING FOR INTERVALS
When using the JavaScript function setInterval(),
you can specify a callback function to be
executed for each interval

setInterval(myFunction, 1000);
function myFunction() {
let d = new Date();

document.getElementById("demo").innerHTML
=
d.getHours() + ":" +
d.getMinutes() + ":" +
d.getSeconds();
}
PROMISES IN JS
A promise is a special JavaScript object that links the
“producing code” and the “consuming code”
together
Producing code
that does something and takes time. For instance,
some code that loads the data over a network

Consuming Code
that wants the result of the “producing code” once
it’s ready. Many functions may need that result
PROMISES IN JS
let promise = new Promise(function(resolve, reject) { //
executor (the producing code)
});

The function passed to new Promise is called the executor.


When new Promise is created, the executor runs automatically. It
contains the producing code which should eventually produce the
result Its arguments resolve and reject are callbacks provided by
JavaScript itself. Our code is only inside the executor.

When the executor obtains the result, be it soon or late, doesn’t


matter, it should call one of these callbacks:

resolve(value) — if the job is finished successfully, with


result value.

reject(error) — if an error has occurred, error is the error object.


PROMISES 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 */ }
);

When the producing code obtains the result, it should call one
of the two callbacks
OnSuccess myResolvle
OnError myReject
PROMISES OBJECT PROPERTIES
A JS promise object supports two properties

State Result
Pending undefined
Fulfilled a result value
Rejected a error object

We can access the promise properties state and


result and must use promise method to handle
promise.
myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
PROMISES EXAMPLE
function display(result) {
document.getElementById("demo").innerHTML = result;
}

let myPromise = new Promise(function(myResolve, myReject) {


let x = 0;

// The producing code (this may take some time)

if (x == 0) {
myResolve("OK");
} else {
myReject("Error");
}
});

myPromise.then(
function(value) {display(value);},
function(error) {display(error);}
);
ASYNC & AWAIT
Async & Await makes promise easier to write
async makes a function result a promise.
await makes a function wait for a promise.

Keyword async before a function makes the function to


return a promise.

async function myFunction(){


return “Asynchronous Programming”
}
Is Same As
function myFunction(){
return Promise.resolve(“Async Programming”)
}
ASYNC & AWAIT
Example Using async keyword
function display(result){

document.getElementById(‘demo’).innerHTML=res
ult
}
async function myFunction() {
return "Hello";
}
myFunction().then(
function(value) {display(value);},
function(error) {display(error);}
);
ASYNC & AWAIT
Await keyword can only be used inside a async
function. The await keyword makes the function
pause the execution and wait for a resolved
promise before it continues.

async function myDisplay() {


let myPromise = new Promise(function(resolve,
reject) {
resolve(“Asynchronous Programming");
});
document.getElementById("demo").innerHTML = await myPro
mise;
}

myDisplay();

You might also like