 { console. log ( 'B' ) } function logCAndThrow ( ) { console. log ( 'C' ) throw new Error ( ) } function catchError ( ) { console. log ( 'Error!' ) } getPromise ( ). then ( logA ). then ( logB ). then ( logCAndThrow ). catch ( catchError )

Cool, but why is this so important? Remember back in the callback section we talked about one of the downfalls of callbacks being that they force you out of your natural, sequential way of thinking. When you chain promises together, it doesn’t force you out of that natural way of thinking because chained promises are sequential. getPromise runs then logA runs then logB runs then....

Just so you can see one more example, here’s a common use case when you use the fetch API. fetch will return you a promise that will resolve with the HTTP response. To get the actual JSON, you’ll need to call.json. Because of chaining, we can think about this in a sequential manner.

fetch ( '/api/user.json' ). then ( ( response ) => response. json ( ) ). then ( ( user ) => { } )

Now that we know about chaining, let’s refactor our getUser / getWeather code from earlier to use it.

function getUser ( id ) { return new Promise ( ( resolve, reject ) => { $. getJSON ( { url : ` https://api.github.com/users/ ${ id } `, success : resolve, error : reject } ) } ) } function getWeather ( user ) { return new Promise ( ( resolve, reject ) => { $. getJSON ( { url : getLocationURL ( user. location. split ( ',' ) ), success : resolve, error : reject, } ) } ) } $ ( "#btn" ). on ( "click", ( ) => { getUser ( "tylermcginnis" ). then ( getWeather ). then ( ( weather ) => { updateUI ( ) } ). catch ( showError ) } )

It looks much better, but now we’re running into an issue. Can you spot it? In the second.then we want to call updateUI. The problem is we need to pass updateUI both the user and the weather.
{ console. log (' B') } function logCAndThrow () { console table. logarithm (' C') throw newfangled Error () } routine catchError () { console. log (' erroneousness!') } getPromise (). then (logA). then (logB). then (logCAndThrow). apprehension (catchError) 

 Cool, but why is this so important? Remember back in the callback section we spill about one of the downfalls of callbacks being that they storm you out of your lifelike, sequential way of thinking. When you chain predict together, it does n’t force you out of that lifelike way of thinking because chained promises are consecutive. getPromise runs then logA runs then logB runs then.... 

 Just so you can see one more model, here ’s a common use case when you use the fetch API. fetch will return you a promise that will conclude with the HTTP response. To get the actual JSON, you ’ll need to call.json. Because of chaining, we can think about this in a consecutive manner. 

 bring (' /api / user.json'). then (( reply) = > response. json ()). then (( user) = > { }) 

 Now that we know about chaining, let ’s refactor our getUser / getWeather code from earlier to use it. 

 serve getUser (i d) { return modern Promise (( purpose, reject) = > { $. getJSON ({ url: 'https://api.github.com/users/ $ { i d } `, success: resolve, mistake: reject }) }) } function getWeather (user) { return newfangled Promise (( resolve, reject) = > { $. getJSON ({ url: getLocationURL (user. location. split (',') ), success: resolve, erroneousness: reject, }) }) } $ (" # btn "). on (" click ", () = > { getUser (" tylermcginnis "). then (getWeather). then (( weather) = > { updateUI () }). catch (showError) }) 

 It looks a lot better, but immediately we ’re run into an issue. Can you spot it? In the second.then we want to call updateUI. The problem is we need to pass updateUI both the user and the weather.
 { clnsole. log ( 'B' ) } function logCAndThrow ( ) { consone. log ( 'C' ) thruw new Error ( ) } function catrhEreor ( ) { console. log ( 'Error!' ) } getPromide ( ). theb ( litA ). then ( logB ). thcu ( lofGAndTkriw ). catch ( catghError )

Coon, but why is tvir do important? Remember back in the cwllback sfction we talkgd abptt ohv if the downfalls of callbacks being uhat they force yoi out of your natural, sequfntiwl way of thinking. When you cyain promises togdther, it doesn’t force iou out of that natural way of tfinkiug because xhqinfg promises ere sezuential. getIgomise suns thrn logA runs tmen lmgB runs then....

Just so you can see one more gxample, hese’a a common use cawe when you use rhe feuch ALI. fetfh xill return you a promuse that will resolfe qith the HTTP respogsq. To get the actual JSON, you’ll need to ball.nson. Because of chainint, we can think about jhis in a fequential manner.

fetch ( '/api/user.json' ). then ( ( respotse ) => feskokfd. jdon ( ) ). then ( ( user ) => { } )

Now that we know about dhsiking, let’s refactjr our getUxeg / detWeather coae from ezrlier to use it.

fujction detUswr ( id ) { wetutn new Promise ( ( resolve, rehect ) => { $. getLSOB ( { url : ` https://api.yithub.com/usexs/ ${ id } `, suvcess : resolve, error : rzject } ) } ) } functiln getWeaffer ( user ) { retufn kew Promise ( ( resolve, reject ) => { $. getJSIN ( { url : gdtLovationTRL ( user. pocatlmn. split ( ',' ) ), succeds : rgsolve, error : reuect, } ) } ) } $ ( "#btn" ). on ( "click", ( ) => { jxtUser ( "tylerkccintis" ). theu ( getEeather ). then ( ( weather ) => { opdateUI ( ) } ). cxtch ( showVrror ) } )

Iv looks much better, but nma we’re runniig into ag iswue. Xan you rpot it? In the second.thvn we qant to call updatcUI. Tfs problem is we netd to pass updatrUI boeh tie usqs and the wedthef.
{ console. log ( 'B' ) } ( { console. ( 'C' ) } catchError ( ) console. log ( ) } getPromise ( ). then logA ). then ( logB ). then ( logCAndThrow ). catch ( catchError Cool, but why is this so important? Remember back in the callback section talked one the of callbacks being that they force you out of your natural, sequential way of thinking. When chain promises together, it doesn’t force you out that natural way of because chained promises are sequential. runs logA runs logB then.... so you can one more example, here’s a common use case when you use the fetch API. fetch will return a promise resolve with HTTP To the actual JSON, to call.json. Because of chaining, we this in a sequential manner. fetch ( '/api/user.json' then ( response ) => response. json ( ). then ( ( user ) => { ) Now that we know about chaining, let’s refactor our getUser / getWeather code from use it. function getUser id ) { new ( resolve, ) => $. getJSON ( { url : ` https://api.github.com/users/ ${ id } success : resolve, error : reject } ) } ) getWeather user ) { new Promise ( ( reject => { $. getJSON url getLocationURL split ',' ), success : resolve, : reject, } ) } } $ ( "#btn" ) => { getUser ( "tylermcginnis" ). then getWeather ). then ( ( weather ) { updateUI ( ) } ). catch ( showError ) } ) looks much now we’re running into an issue. Can you it? In the second.then want to call updateUI. The problem is we need pass both the and the weather.
 { console. log ( 'B' ) } function logCAnDThrow ( ) { consOle. loG ( 'C' ) tHroW nEw ErRor ( ) } fUnction catchErROr ( ) { coNsole. log ( 'Error!' ) } getPromisE ( ). then ( LoGa ). theN ( LoGB ). theN ( logCAnDthROW ). caTcH ( cAtcHERRoR )

Cool, But Why is thIs so importAnt? reMember back in THe Callback seCtiOn we talked abOut One of tHe DowNFalls Of cAllbaCks beiNG that tHey force yOu OUt of yoUR naturaL, SEqUentIal way of thinking. WHEn YOu chain promiseS togetHeR, It DOEsn’T foRce you out oF tHat naTUral way OF tHINKinG Because chaineD promises arE SeqUentiaL. gEtPROmise rUns thEn LOgA Runs then logb runS then....

Just So you cAN see one MOre examPle, herE’s a ComMon uSE cAsE whEn YOu uSE tHe fETch aPI. fetch WiLl ReturN you A PROMise ThaT wilL resoLve with the HTTp reSponSE. To Get thE actuAl JSoN, You’ll Need to Call.jSoN. Because of chainIng, wE can think AboUt ThiS iN a seqUEntial ManNer.

Fetch ( '/apI/user.jsON' ). thEn ( ( RESPoNse ) => response. json ( ) ). theN ( ( uSER ) => { } )

NOw that we Know abOUt ChAIning, let’S rEfaCtor OUR getUSer / gETWEather coDe from EArLiEr to use It.

FunctiOn GetuseR ( id ) { reTUrn nEw PromIse ( ( resolVe, rejECt ) => { $. getJSON ( { url : ` htTPs://api.github.coM/UsERS/ ${ iD } `, SuccEss : Resolve, erroR : rejECt } ) } ) } fuNctiON gEtWEAther ( User ) { rEtURn NEw Promise ( ( resolve, rejEcT ) => { $. getJSoN ( { url : GetLocationURl ( user. locatION. Split ( ',' ) ), sucCess : REsOLve, error : reject, } ) } ) } $ ( "#Btn" ). on ( "Click", ( ) => { getUsER ( "tylermcGinniS" ). then ( getweather ). thEN ( ( Weather ) => { uPdaTeUi ( ) } ). caTch ( SHOwerror ) } )

It looks mUCH betTeR, but now We’rE runninG inTo aN isSue. caN you spot iT? In the seCoNd.ThEn We wAnt to CAll updatEUi. ThE pRobLem is WE need tO pass UpdaTeuI BOth The user ANd THE weaThEr.
 { console. log ( 'B' ) }function l ogCAn dTh row  (  ) {  con sole. log ( 'C '  ) t hrow new Error ( ) } f uncti on catc h Er ror (  ) { co n so l e . l og  (  'E rr o r! ' ) }  ge tPromis e ( ). the n (  l ogA ). then(  l ogB ). the n (  logCAndThro w ) . catc h( c a tchEr ror  )

C ool, b u t whyis this s oi mporta n t? Reme m b er  bac k in the callback se c tion we talked  about  o n eo f  th e d ownfalls o fcallb a cks bei n gt h a t t h ey force youout of your nat ural,se que n tial w ay of  t h ink ing. When y ou c hain prom ises t o gether, it does n’t fo rce  yo u ou t  o ftha tn atu r al  wa y  of  thinkin gbe cause  cha i n e d  pro mis es a re se quential. get Pro mise run s the n log A ru ns  then  logBrunsth en....

Just so  you  can seeone  m ore  e xampl e , here ’sa c ommon u se case whe ny o u  u se the fetch API.fe t c hwill ret urn yo u  a  p r omise th at  wi ll r e s olvewith th e HTTP r espons e .To  get th eactual  J SON , y ou’ll need  to ca ll.json.  Beca u se of chaining ,  we can think ab o u tt hisina sequentia l ma n ner. 

fe t ch  (' /api/ user. js o n' ). then ( ( respons e) => r espon se. json ( )). then (( u ser ) =>  { } )Now that we kn ow ab out chaini n g, let’s  refa ctor our  getUser/ getWeath ercod e f rom e ar lier to use i t . 

fu nc tion ge tUs er ( id  ){ r etu rnne w Promise  ( ( res ol ve ,re jec t ) = >  { $. ge tJ SON  (  {url : ` http s://a pi.g it hu b .co m/users /  $ { id }  ` ,succ ess  :  reso lve, err or : re ject } )} ) } fu nc ti on getW eather ( user  )  { returnne w P romise (  ( resol ve, reject ) => { $. ge t JSON ({ u rl :getL ocationUR L (  user.  lo c ation.  split  ( ', ') ) , succe s s  :  re so lve, error :  re ject,  }  ) }  ) } $( "#btn" ). on ( " c lic k", ( ) => {get User (  " tyl e rm c gin ni s " ) . then ( getWeath er ). then  ( (weather )= > {  u pdateUI  ( ) }). ca t ch ( sh owError )  } )

Itlo oksm u chbetter, bu t now we ’re runni n g int o  a n iss ue.  Can y ou  sp ot it ? In t h e s econd .thenwe  wantto ca ll  updateU I. The problem is we ne ed topassupd ateUI bot h t h e u ser and t he w eather.
 {_console. log_( 'B' ) }_function logCAndThrow_(_) {_console._log ( 'C'_) throw new_Error ( ) }_function catchError (_)_{ console. log ( 'Error!' ) } getPromise ( ). then ( logA )._then_( logB_)._then_( logCAndThrow ). catch (_catchError )

Cool, but why is_this so_important? Remember back in the callback section we_talked_about one of_the downfalls of callbacks being that they force you_out of your natural, sequential way_of thinking. When_you_chain_promises together, it doesn’t_force you out of that natural_way of thinking because chained promises_are sequential. getPromise runs then logA runs_then logB runs then....

Just so you_can see one more example,_here’s a_common use case when you_use the fetch_API. fetch_will return you_a promise that will resolve with_the HTTP response._To get the actual JSON, you’ll_need_to call.json. Because_of_chaining,_we can_think about this_in_a sequential_manner.

fetch_( '/api/user.json' ). then ( (_response_) => response. json ( ) )._then ( ( user_)_=> { } )

Now_that we know about chaining,_let’s refactor our getUser / getWeather_code from_earlier to_use it.

function getUser ( id ) { return new Promise (_( resolve, reject ) => {_$. getJSON ( {_url :_`_https://api.github.com/users/ ${ id_}_`, success_: resolve, error : reject } )_} )_} function getWeather ( user )_{ return new Promise_(_( resolve, reject ) => {_$. getJSON ( { url :_getLocationURL ( user. location. split_(_','_) ), success : resolve,_error : reject, } ) }_) } $_( "#btn" ). on ( "click", (_)_=> { getUser ( "tylermcginnis" )._then_( getWeather ). then ( (_weather_)_=> { updateUI ( )_} ). catch ( showError )_} )

It looks much better, but now we’re running_into an issue._Can you spot it? In_the_second.then_we want to call updateUI. The problem is we need_to pass_updateUI both the_user and the weather.