Advertisement
Guest User

Nice To Debug and Understand

a guest
Jul 21st, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Legacy function with callbacks
  2. function doShit(key, callback) {
  3.     if(key == 1) {
  4.         callback(null, 'SUCCESS');
  5.     } else {
  6.         callback(new Error('Not one'), null);
  7.     }
  8. }
  9.  
  10. // Consuming Legacy code
  11. doShit(1, (error, val) => {
  12.     if(error)
  13.       console.log("Error occured and while doing shit. " + error);
  14.     else
  15.       console.log("Shit is done, horray :D.  " + val)
  16. });
  17.  
  18. // Wrapping doShit function with Promise API
  19. function doShitWithPromise(key) {
  20.     return new Promise((resolve, reject) => {
  21.         doShit(key, (error, val) => {
  22.             if(error) reject(error);
  23.             else resolve(val);
  24.         });
  25.     });
  26. }
  27.  
  28. // Consuming new doShit function style with promise
  29. var shitPromise = doShitWithPromise(2)
  30.     .then((val) => console.log("Shit is done, horray :D.  " + val))
  31.     .catch((error) => console.log("Error occured and while doing shit. " + error));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement