var promise =newPromise(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 inJavaScript.They are easy to manage when dealing with multiple asynchronous operations
where callbacks can create callback hell leading to unmanageable code.
let promise =newPromise((resolve,reject)=>{try{resolve("some data");}catch(error){reject(error);}})
promise.then(function(data){console.log(data);},function(error){console.error(error);})
// 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 =newPromise(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"
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._____________________________________varasyncronus_function=(number)=>{returnnewPromise((accept, reject)=>{})}
_____________________________________
thisfunctionreturn a promise Object, thet required a function executor
thisfunctions(accept, reject) are defined in the executor
function, that was needed in promise constructor.Syntax:newPromise(executor)executor=(accept, reject)=>{}iffunction end well we return a accept(), otherwise reject()
_____________________________________
Let complete asyncronus_function
_____________________________________
varasyncronus_function=(number)=>{returnnewPromise((accept, reject)=>{if(number>10)returnaccept("my first async");returnreject("my first async error")})}if it dont return any ofthis2function,Promise state is [PENDING],ifreturn accept is [RESOLVED] end ifreturn reject is [REJECTED]
_____________________________________
how we can retrieve accept or reject?
_____________________________________
there is two methods really important, that we have to consider afther we call thisfunction1).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)});ifMY_NUMBER>10,asyncronus_function print data :OUTPUT my first asyncifMY_NUMBER<10, asyncronus_function print error :OUTPUT my first async error
HOPE it halp and have a nice day!
const myScore=500;functioncheckNumnbner(){console.log('Course Enrolment Process');const myPromise=newPromise((resolve , reject)=>{if(myScore >=80){resolve("First one is true");}else{setTimeout(()=>{reject("SORRY we CANT offering you a job")},2000);}})return myPromise;}functionofferLater(){const newPromise2=newPromise((resolve)=>{setTimeout(()=>{resolve("congratulation we are offering you a job")},500);})return newPromise2;}functionthanksT(){constEnd=newPromise(()=>{setTimeout(()=>{console.log(('Thanks to try'));},2000)})returnEnd}checkNumnbner().then(offerLater).then(value=>console.log(value)).then(thanksT).catch((error)=>{console.log(error);})
const myPromise =newPromise((resolve, reject)=>{let condition;if(condition is met){resolve('Promise is resolved successfully.');}else{reject('Promise is rejected');}});
/*
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 =newPromise((resolve, reject)=>{});
let num =10;//call back functionconst promis =newPromise(function(resolve, reject){if(num >5){//this resolve method will send data to resoleveData variableresolve(" Problem resolved successfully")}else{//this reject method will send data to rejectData variablereject("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 rejectedconstA=newPromise((resolve, reject)=>{setTimeout(()=>{// here we pass argument if promise get resolvedresolve('Done');// here we pass argument if promise get rejectedreject('Didn"t');},3000);});// design handling callback function for resolve lethandleResolvedA=(massage)=>{console.log(massage)}// design handling callback function for reject lethandleRejectedA=(massage)=>{console.log(massage)}// do handling for bothA.then(handleResolvedA, handleRejectedA)
const promiseA =newPromise((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
var myImage =document.querySelector('#example');functionloaded(){// bien, la imagen cargó}if(myImage.complete){loaded();}else{
myImage.addEventListener('load', loaded);}
myImage.addEventListener('error',function(){// ocurrió un imprevisto});
let num =2;//call back functionconst promis =newPromise(function(resolve, reject){if(num >5){//this resolve method will send data to resoleveData variableresolve(" Problem resolved successfully")}else{//this reject method will send data to rejectData variablereject("sorry problem couldn't solve")}})
promis.then(//resoleveData variablefunction(resolveData){console.log(resolveData)}).catch(//rejectData variablefunction(rejectData){console.log(rejectData)})
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 ofasync opertion or failue ofasync operations
APromise is in one of these states:pending: initial state, neither fulfilled nor rejected.fulfilled: meaning that the operation was completed successfully.rejected: meaning that the operation failed.