|
| 1 | +//callback hell |
| 2 | +/*function callbackHell(){ |
| 3 | + setTimeout(()=> { |
| 4 | + console.log("Callback 1"); |
| 5 | + setTimeout(()=> { |
| 6 | + console.log("Callback 2"); |
| 7 | + setTimeout(()=> { |
| 8 | + console.log("Callback 3"); |
| 9 | + setTimeout(()=>{ |
| 10 | + console.log("Callback 4"); |
| 11 | + },3000) |
| 12 | + },2000) |
| 13 | + },1000) |
| 14 | + },1000) |
| 15 | +} |
| 16 | +callbackHell(); |
| 17 | +//In the above example we are using an async function setTimeout and passing an arrow function as a parameter , Thus when a function is passes into another function as parameter it is called as callback function |
| 18 | +//Callbacks inside callbacks create an ugly syntax and pyramid of dooom , to avoid this we use promises |
| 19 | +
|
| 20 | +const p = new Promise (function(resolve){ |
| 21 | + let output = setTimeout(()=>{ |
| 22 | + console.log("Callback 1"); |
| 23 | + resolve(output); |
| 24 | + },1000) |
| 25 | +}) |
| 26 | +p.then(function(resolve){ |
| 27 | + setTimeout(()=>{ |
| 28 | + console.log("Callback 2") |
| 29 | + },10000); |
| 30 | +}) |
| 31 | +.then(function(resolve){ |
| 32 | + setTimeout(()=>{ |
| 33 | + console.log("Callback 3") |
| 34 | + },1000); |
| 35 | +}) |
| 36 | +console.log(p); |
| 37 | +*/ |
| 38 | + |
| 39 | +const pro = new Promise(function(resolve) { |
| 40 | + let output = setTimeout(() => { |
| 41 | + console.log("Callback 1"); |
| 42 | + resolve(output); // Resolving with the timeout ID |
| 43 | + }, 1000); |
| 44 | +}); |
| 45 | + |
| 46 | +pro.then(function(output) { // Using the resolved value from the Promise |
| 47 | + return new Promise(function(resolve) { |
| 48 | + setTimeout(() => { |
| 49 | + console.log("Callback 2"); |
| 50 | + resolve(); // Resolving without a value |
| 51 | + }, 10000); |
| 52 | + }); |
| 53 | +}) |
| 54 | +.then(function() { |
| 55 | + return new Promise(function(resolve) { |
| 56 | + setTimeout(() => { |
| 57 | + console.log("Callback 3"); |
| 58 | + resolve(); // Resolving without a value |
| 59 | + }, 1000); |
| 60 | + }); |
| 61 | +}); |
| 62 | + |
| 63 | +console.log(pro); // Logging the Promise object |
| 64 | + |
0 commit comments