1var promise = new Promise(function(resolve, reject) {
2 // do some long running async thing…
3
4 if (/* everything turned out fine */) {
5 resolve("Stuff worked!");
6 }
7 else {
8 reject(Error("It broke"));
9 }
10});
11
12//usage
13promise.then(
14 function(result) { /* handle a successful result */ },
15 function(error) { /* handle an error */ }
16);
1let promise = new Promise(function(resolve, reject){
2 try{
3 resolve("works"); //if works
4 } catch(err){
5 reject(err); //doesn't work
6 }
7}).then(alert, console.log); // if doesn't work, then console.log it, if it does, then alert "works"
1/*
2Promise is a constructor function, so you need to use the new keyword to
3create one. It takes a function, as its argument, with two parameters -
4resolve and reject. These are methods used to determine the outcome of the
5promise.
6The syntax looks like this:
7*/
8
9const myPromise = new Promise((resolve, reject) => {
10
11});
12
13
1const promiseA = new Promise( (resolutionFunc,rejectionFunc) => {
2 resolutionFunc(777);
3});
4// At this point, "promiseA" is already settled.
5promiseA.then( (val) => console.log("asynchronous logging has val:",val) );
6console.log("immediate logging");
7
8// produces output in this order:
9// immediate logging
10// asynchronous logging has val: 777
11
1myPromise.then(
2 function(value) { /* code if successful */ },
3 function(error) { /* code if some error */ }
4);
1var posts = [
2 {name:"Mark42",message:"Nice to meet you"},
3 {name:"Veronica",message:"I'm everywhere"}
4];
5
6function Create_Post(){
7 setTimeout(() => {
8 posts.forEach((item) => {
9 console.log(`${item.name} --- ${item.message}`);
10 });
11 },1000);
12}
13
14function New_Post(add_new_data){
15 return new Promise((resolve, reject) => {
16 setTimeout(() => {
17 posts.push(add_new_data);
18 var error = false;
19 if(error){
20 reject("Something wrong in </>, Try setting me TRUE and check in console");
21 }
22 else{
23 resolve();
24 }
25 },2000);
26 })
27}
28
29New_Post({name:"War Machine",message:"I'm here to protect"})
30 .then(Create_Post)
31 .catch(err => console.log(err));