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 */ }
);
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.
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);
})
/*
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
});
const count = true;
let countValue = new Promise(function (resolve, reject) {
if (count) {
resolve("There is a count value.");
} else {
reject("There is no count value");
}
});
console.log(countValue);
// Promise is a special type of object that helps you work with asynchronous operations.
// Many functions will return a promise to you in situations where the value cannot be retrieved immediately.
const userCount = getUserCount();
console.log(userCount); // Promise {<pending>}
// In this case, getUserCount is the function that returns a Promise. If we try to immediately display the value of the userCount variable, we get something like Promise {<pending>}.
// This will happen because there is no data yet and we need to wait for it.
let promise = new Promise(function(resolve, reject){
try{
resolve("works"); //if works
} catch(err){
reject(err); //doesn't work
}
}).then(alert, console.log); // if doesn't work, then console.log it, if it does, then alert "works"
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 */ }
);
/*
Promise is a constructor function, so you need to use the new keyword to
create one. It takes a function, as its argument, with two parameters -
resolve and reject. These are methods used to determine the outcome of the
promise.
The syntax looks like this:
*/
const myPromise = new Promise((resolve, reject) => {
});
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)
})
// make new promise ... so this object will promise us that it will hold an Asynchronous action
// some times promise resolve and some times promise get rejected
const A = new Promise((resolve, reject) => {
setTimeout(() => {
// here we pass argument if promise get resolved
resolve('Done');
// here we pass argument if promise get rejected
reject('Didn"t');
}, 3000);
});
// design handling callback function for resolve
let handleResolvedA = (massage)=>{console.log(massage)}
// design handling callback function for reject
let handleRejectedA = (massage)=>{console.log(massage)}
// do handling for both
A.then(handleResolvedA, handleRejectedA)
const promiseA = new Promise( (resolutionFunc,rejectionFunc) => {
resolutionFunc(777);
});
// At this point, "promiseA" is already settled.
promiseA.then( (val) => console.log("asynchronous logging has val:",val) );
console.log("immediate logging");
// produces output in this order:
// immediate logging
// asynchronous logging has val: 777
A promise is an object that may produce a single value sometime in the future: either a resolved value, or a reason that it's not resolved (e.g., a network error occurred)
Promises make async javascript easier as they are easy to use and write than callbacks. Basically , promise is just an object , that gives us either success of async opertion or failue of async operations