Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*** BROSWER W/ FETCH API ***/
- /*
- Let's say that we're posting credentials to some API,
- and then performing a get request to some protected resource
- with the credentials (i.e. cookie, JWT, etc.) that is returned
- to us from the first API call
- */
- var firstApiUrl = ''
- fetch(firstApiUrl, {
- method: 'POST',
- body: JSON.strinfiy({username: '', password: ''})
- }).then(function(res) {
- var apiKey = JSON.parse(res.data)
- // fetch returns a promise, so we can continue chaining
- var secondApiUrl = ''
- return fetch(secondApiUrl + '?key=' + apiKey, { method: 'GET' })
- }).then(function(res) {
- var data = JSON.parse(res.data)
- // This illustrates an explicit return of a promise
- return new Promise(function(resolve, reject) {
- resolve("Hi Charlie!")
- })
- }).then(function(value){
- // Value here is what the last promise resovled as so
- console.log(value) // "Hi Charlie!"
- // Now let's throw an error
- return new Promise(function(reoslve, reject) {
- reject(new Error('Sad face :('))
- })
- }).catch(function(err) {
- // This catches the error at any point in the promise chain
- // but let's assume they all resolved except the last .then where we rejected w/ an error
- console.log('Error performing API call(s)', err) // 'Error performing api Call(s) Sad face :('
- })
- /*** NODE CALLBACKS ***/
- // this is an imaginary rest client, the point is that it uses callbacks in our imaginary api
- var rest = require('')
- rest.post(firstApiUrl, JSON.stringify({username: '', password: ''}), function callback(err, res) {
- if (err) {
- console.log('Error!', err)
- // return to prevent next api from being called
- return
- }
- rest.get(secondApiUrl, function(err, res) {
- if (err) {
- // we have to handle errors at every step, unlike promises
- console.log('Error!', err)
- return
- }
- // another async function
- databaseClient.write(res.data, function(err) {
- if (err) {
- console.log('Error writing to database', err)
- }
- })
- })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement