Advertisement
Guest User

Untitled

a guest
Apr 28th, 2016
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*** BROSWER W/ FETCH API ***/
  2. /*
  3.     Let's say that we're posting credentials to some API,
  4.     and then performing a get request to some protected resource
  5.     with the credentials (i.e. cookie, JWT, etc.) that is returned
  6.     to us from the first API call
  7. */
  8.  
  9. var firstApiUrl = ''
  10. fetch(firstApiUrl, {
  11.     method: 'POST',
  12.     body: JSON.strinfiy({username: '', password: ''})
  13. }).then(function(res) {
  14.     var apiKey = JSON.parse(res.data)
  15.      
  16.     // fetch returns a promise, so we can continue chaining
  17.     var secondApiUrl = ''
  18.     return fetch(secondApiUrl + '?key=' + apiKey, { method: 'GET' })
  19. }).then(function(res) {
  20.     var data = JSON.parse(res.data)
  21.  
  22.     // This illustrates an explicit return of a promise
  23.     return new Promise(function(resolve, reject) {
  24.         resolve("Hi Charlie!")
  25.     })
  26. }).then(function(value){
  27.     // Value here is what the last promise resovled as so
  28.     console.log(value) // "Hi Charlie!"
  29.    
  30.     // Now let's throw an error
  31.     return new Promise(function(reoslve, reject) {
  32.         reject(new Error('Sad face :('))
  33.     })
  34. }).catch(function(err) {
  35.     // This catches the error at any point in the promise chain
  36.     // but let's assume they all resolved except the last .then where we rejected w/ an error
  37.    
  38.     console.log('Error performing API call(s)', err) // 'Error performing api Call(s) Sad face :('
  39. })
  40.  
  41.  
  42. /*** NODE CALLBACKS ***/
  43.  
  44. // this is an imaginary rest client, the point is that it uses callbacks in our imaginary api
  45. var rest = require('')
  46.  
  47. rest.post(firstApiUrl, JSON.stringify({username: '', password: ''}), function callback(err, res) {
  48.     if (err) {
  49.         console.log('Error!', err)
  50.         // return to prevent next api from being called
  51.         return
  52.     }
  53.    
  54.     rest.get(secondApiUrl, function(err, res) {
  55.         if (err) {
  56.             // we have to handle errors at every step, unlike promises
  57.             console.log('Error!', err)
  58.             return
  59.         }
  60.        
  61.         // another async function
  62.         databaseClient.write(res.data, function(err) {
  63.             if (err) {
  64.                 console.log('Error writing to database', err)
  65.             }
  66.         })
  67.     })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement