Advertisement
Guest User

Untitled

a guest
May 22nd, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. const axios = require('axios');
  2. const request = require('request');
  3. /*
  4. issue with this approach:
  5. - nested: bad design, no limit of how many levels functions can be nested, arguments from callback(err, body) have to
  6. renamed constantly to prevent overlap
  7. - readability: not very readable, may need to nest multiple times
  8. - usability: as a provider of functions, need to maintain callback as last argument
  9. */
  10. //request.get('http://google.com.sg',{query :{ name: "hello"}}, (err, body)=>{
  11. request.get('http://google.com.sg', (err, body)=>{
  12. if(err){
  13. console.log("do something with error");
  14. return;
  15. }
  16. console.log("do something with data");
  17. request.get('http://youtube.com.sg', (err2, body)=>{
  18. if(err2){
  19. console.log("do something with error nested");
  20. return;
  21. }
  22. console.log("do something with data nested");
  23. })
  24. });
  25. /*
  26. Promises explained as callbacks:
  27. - if err is null , the function passed to "then" will be called(successful)
  28. - if err is not null, the function passed to "catch" will be called(error)
  29. Benefits:
  30. - although then and catch accepts a function, as promises are returned and not defined in how u call the function(referring to callbacks),
  31. you can just return another function which returns a function
  32. - err and body are separated, do not need to have ugly syntax of line 11 - 14, what to do when successful and error are clearly defined and seperated
  33. - no need to maintain rule of having callback last argument to function
  34. */
  35. /*axios.get("http://google.com.sg",{
  36. query: {
  37. name: "hello"
  38. }
  39. })*/
  40. axios.get("http://google.com.sg").then((body)=>{
  41. console.log("do something with data");
  42. return axios.get("http://youtube.com.sg");
  43. }).catch((err)=>{
  44. console.log("do something with error");
  45. }).then((body)=>{
  46. console.log("do something with data another then");
  47. }).catch((err)=>{
  48. console.log("do something with error");
  49. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement