xxxxxxxxxx
We use promise to make a AsyncFunction, cose simetime we have to wait that function give
us some result.
Example, if we use ajax we have await ajax data or statament.
_____________________________________
Make a simple example.
_____________________________________
var asyncronus_function= (number)=>
{
return new Promise( (accept, reject)=>
{
})
}
_____________________________________
this function return a promise Object, thet required a function executor
this functions (accept, reject) are defined in the executor
function, that was needed in promise constructor.
Syntax: new Promise (executor)
executor= (accept, reject) =>{}
if function end well we return a accept(), otherwise reject()
_____________________________________
Let complete asyncronus_function
_____________________________________
var asyncronus_function= (number)=>
{
return new Promise( (accept, reject)=>
{
if(number>10)
return accept("my first async");
return reject("my first async error")
})
}
if it dont return any of this 2 function, Promise state is [PENDING] ,
if return accept is [RESOLVED] end if return reject is [REJECTED]
_____________________________________
how we can retrieve accept or reject?
_____________________________________
there is two methods really important, that we have to consider afther we call this function
1) .then(function(error){}) is call when promise state is [RESOLVED]
2) .error(function(error){}) is call when promise state is [REJECTED]
3) do nothing if [PENDING]
_____________________________________
let call asyncronus_function()!!!
_____________________________________
asyncronus_function(MY_NUMBER).then(function(data)
{
console.log(data)
}).catch(error =>
{
console.log(error)
});
if MY_NUMBER> 10 ,asyncronus_function print data : OUTPUT my first async
if MY_NUMBER<10 , asyncronus_function print error : OUTPUT my first async error
HOPE it halp and have a nice day!
xxxxxxxxxx
let conditions=true;
const proms= new Promise((resolve, reject) => {
setTimeout(() => {
if (conditions) {
resolve ("Hello")
} else {
reject ("This condition faild")
}
}, 2000);
});
proms.then((result) => {
console.log(result);
})
.catch(function(error){
console.log(error);
});
xxxxxxxxxx
var promise = new Promise(function(resolve, reject) {
// do some long running async thing…
if (/* everything turned out fine */) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});
//usage
promise.then(
function(result) { /* handle a successful result */ },
function(error) { /* handle an error */ }
);
xxxxxxxxxx
Promises are used to handle asynchronous operations in JavaScript.
They are easy to manage when dealing with multiple asynchronous operations
where callbacks can create callback hell leading to unmanageable code.
xxxxxxxxxx
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const promise = new Promise((resolve, reject) => {
setTimeout(()=>{
let flag = 0; // true fasle 1 or 0
if(!flag){
resolve({name:'Malik Amir Hamza' , id:1});
}
else{
reject('error something went wrong');
}
},2000);
});
promise
.then((user)=>{console.log(user)})
.catch((error)=>{console.log(error)});
</script>
</body>
</html>
xxxxxxxxxx
//promise is an object that give result of request or reject request
//creation of promise
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('got the user');
// resolve({ user: 'shirshak' });
reject(new Error('User not logged in'));
}, 2000);
});
//consume of promise
promise
.then(user => {
console.log(user);
})
.catch(err => console.log(err.message));
xxxxxxxxxx
let promise = new Promise((resolve,reject)=>{
try {
resolve("some data");
} catch (error) {
reject(error);
}
})
promise.then(function (data) {
console.log(data);
},function (error) {
console.error(error);
})
xxxxxxxxxx
----------------------------------------
Promise.all() allSettled() race()
----------------------------------------
* Promise.all() :
- all() method is used when all promises are expected to return the
resolved state.
- showing result at a particular follow sequence.
// Example:
const p1 = new Promise((resolve,reject)=>{
setTimeout(()={ resolve("Promise3"); },2000) );
Promise.all([p1,p2,p3]).then((prMsgs)=>{ console.log(prMsgs); })
* Promise.allSettel():
- showing all the result regardless resolve or reject
- It will show resolve or reject promises one by one.
* Promise.race():
- From the list of promises if any promise returns the result first
then it will show that promise result.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Promise :
//Simple promise example:
const data = new Promise((resolve, reject) => {
if (1 > 3) {
resolve('Working fine')
} else {
reject('Something wrong')
}
})
data.then((res) => {
console.log(`Success=>`, res)
})
data.catch((err) => {
console.log(`Error=>`, err)
})
xxxxxxxxxx
const studentRol=new Promise((resolve, reject) => {
setTimeout(()=>{
/**this function will give the value Of tageted studebt Roll number */
let RollOffStd=[1,2,3,4,5,6,7,8];
for (let index = RollOffStd[RollOffStd.length-1]+1 ; index <50; index++) {
RollOffStd.push(index)
}
resolve( RollOffStd)
reject('My name is Noor mohammad ')
},1000)
})
const mybiodata=(gRollOfStudent /* this is First parameter OF ( mybiodata function ) and You can change parameter value */)=>{
return new Promise((resolve, reject) => {
setTimeout((x) => {
let bio={
myname : 'Noor mohammad Patwary ' ,
age : 25 ,
}
resolve(`my name is ${bio.myname } and my age = ${bio.age } and my roll is =${x} ` )
}, 1000,gRollOfStudent);
})
}
studentRol.then(( RollOfStudent)=>{
console.log(RollOfStudent); /** From here we are gating the Value OF student roll number */
mybiodata(RollOfStudent[1] /* this is First Argument OF ( mybiodata function )*/).then((fff)=>{
console.log(fff);
})
}).catch((x)=>{
console.log(x);
})
xxxxxxxxxx
/*
A promise is a building object of JavaScript, using it we can easily do
asynchronous tasks. Also, the concept that is used to create clean code
basically promises.
*/
//Promise
let firstPromise = new Promise((resolved, reject) => {
let fullName = 'Muhammad Shahnewaz';
setTimeout(() => resolved(fullName), 3000); //we need to use setTimeout()
}).then((name) => {
console.log('I am ' + name); //Muhammad Shahnewaz
});
xxxxxxxxxx
let num = 10;
//call back function
const promis = new Promise(function (resolve, reject) {
if (num > 5) {
//this resolve method will send data to resoleveData variable
resolve(" Problem resolved successfully")
}
else {
//this reject method will send data to rejectData variable
reject("sorry problem couldn't solve")
}
})
//resoleveData variable
promis.then(function (resolveData) {
console.log(resolveData)
//rejectData variable
}).catch(function (rejectData) {
console.log(rejectData)
})