1// base case
2promise
3 .then(...)
4 .then(...)
5 .then(...)
6 .catch(...)
7
8//real world
9coinflip(10)
10 .then(betAgain)
11 .then(betAgain)
12 .then(betAgain)
13 .then(result => {
14 console.log(`OMG, WE DID THIS! TIME TO TAKE ${result} HOME!`);
15 })
16 .catch(handleRejection);
1new Promise(function(resolve, reject) {
2
3 setTimeout(() => resolve(1), 1000); // (*)
4
5}).then(function(result) { // (**)
6
7 alert(result); // 1
8 return result * 2;
9
10}).then(function(result) { // (***)
11
12 alert(result); // 2
13 return result * 2;
14
15}).then(function(result) {
16
17 alert(result); // 4
18 return result * 2;
19
20});
1/* Let's break n STEP-BY-STEP (cpy paste n console u'll have clear view)
2
31. Promises chaining will allow us to add many async operations
4 in a sequence way (i.e in order)
52. But like we have callback hell, here our code at the end
6will be more difficult to read
73. TIPS : Best options are go with >> {FETCH API, Async/Await}
84. NOTE : Learn promises once, understand no.3 in a easy way, above
9both completely relay on Promises concept, makesure u understand them
10clearly. */
11
12
13//EXAMPLE
14
15var result = true;
16var learsJS = new Promise((resolve,reject) => {
17 setTimeout(() => {
18 if(result){ //if true resolve below case
19 resolve("This is my 1st resolved case");
20 }
21 else{
22 reject("I need some more time");
23 }
24 }, 2000);
25}).then(resolvedData1 => {
26 console.log(resolvedData1); //resolved promise1 - 5th line
27 return new Promise((resolve) => { // returning another promise2
28 resolve(`${resolvedData1} -- This is 2nd resolved case`)
29 });
30})
31.then(resolvedData2 => {
32 console.log(resolvedData2); //resolved promise2
33 return new Promise((resolve) => { // returning another promise3
34 resolve(` ${resolvedData2} -- This is my 3rd resolved case`)
35 })
36})
37.then(resolvedData3 => {
38 console.log(resolvedData3); //resolved promise3
39 return new Promise((resolve) => { //returning final promise
40 resolve(` ${resolvedData3} -- This is my Final resolved case`)
41 })
42})
43.then(finalData => console.log(finalData)); //resolved final promise