Created
May 3, 2018 14:30
-
-
Save nikkaroraa/de759bdfc84060c12c2be0b4454f3200 to your computer and use it in GitHub Desktop.
Callbacks, Promises and Async/Await
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // The Problem | |
| function fn(val) { | |
| setTimeout(function() { | |
| console.log(val) | |
| }, val) | |
| } | |
| function executeAll() { | |
| fn(20) | |
| fn(20) | |
| fn(400) | |
| fn(20) | |
| } | |
| executeAll() | |
| // The Solution (through callback) | |
| function fn(val, callback) { | |
| setTimeout(function() { | |
| console.log(val) | |
| callback() | |
| }, val) | |
| } | |
| function executeAll() { | |
| fn(20, function() { | |
| fn(20, function() { | |
| fn(400, function() { | |
| fn(20, function() { | |
| }) | |
| }) | |
| }) | |
| }) | |
| } | |
| executeAll() | |
| // The Solution (through Promise) | |
| function fn(val) { | |
| return new Promise(function (resolve, reject) { | |
| setTimeout(function() { | |
| console.log(val) | |
| resolve() | |
| }, val) | |
| }) | |
| } | |
| function executeAll() { | |
| fn(20).then(function() { | |
| return fn(20) | |
| }).then(function() { | |
| return fn(400) | |
| }).then(function() { | |
| return fn(20) | |
| }) | |
| } | |
| executeAll() | |
| // The Solution (through Async/Await) | |
| function fn(val) { | |
| return new Promise(function (resolve, reject) { | |
| setTimeout(function() { | |
| console.log(val) | |
| resolve() | |
| }, val) | |
| }) | |
| } | |
| async function executeAll() { | |
| await fn(20) | |
| await fn(20) | |
| await fn(400) | |
| await fn(20) | |
| } | |
| executeAll() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment