Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const axios = require('axios');
- const request = require('request');
- /*
- issue with this approach:
- - nested: bad design, no limit of how many levels functions can be nested, arguments from callback(err, body) have to
- renamed constantly to prevent overlap
- - readability: not very readable, may need to nest multiple times
- - usability: as a provider of functions, need to maintain callback as last argument
- */
- //request.get('http://google.com.sg',{query :{ name: "hello"}}, (err, body)=>{
- request.get('http://google.com.sg', (err, body)=>{
- if(err){
- console.log("do something with error");
- return;
- }
- console.log("do something with data");
- request.get('http://youtube.com.sg', (err2, body)=>{
- if(err2){
- console.log("do something with error nested");
- return;
- }
- console.log("do something with data nested");
- })
- });
- /*
- Promises explained as callbacks:
- - if err is null , the function passed to "then" will be called(successful)
- - if err is not null, the function passed to "catch" will be called(error)
- Benefits:
- - although then and catch accepts a function, as promises are returned and not defined in how u call the function(referring to callbacks),
- you can just return another function which returns a function
- - 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
- - no need to maintain rule of having callback last argument to function
- */
- /*axios.get("http://google.com.sg",{
- query: {
- name: "hello"
- }
- })*/
- axios.get("http://google.com.sg").then((body)=>{
- console.log("do something with data");
- return axios.get("http://youtube.com.sg");
- }).catch((err)=>{
- console.log("do something with error");
- }).then((body)=>{
- console.log("do something with data another then");
- }).catch((err)=>{
- console.log("do something with error");
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement