 = refineSource(sourceString)
  sourceArray = combineCommon(sourceArray)
  sourceArray = getWordFreq(sourceArray)
  var obj = sortToObject(sourceArray[0], sourceArray[1])
  console.log(obj)
  return obj
}

A:

A big issue in your asynchronous flow is that you use a shared variable sourceString to handle the results. When you have multiple calls to getNewsApi() your result is not predictable and will not always be the same, because there is no predefined order in which the asynchronous calls are executed. Not only that, but you never reset it, so all subsequent calls will also include the results of the previous calls. Avoid modifying shared variables in asynchronous calls and instead use the results directly.

I've been able to use underscore's _.after and request-promise to make my app wait till all API calls have completed before calling processWordBank()

Although it would possible to use _.after, this can be done very nicely with promises, and since you're already using promises for your requests, it's just a matter of collecting the results from them. So because you want to wait until all API calls are completed you can use Promise.all which returns a promise that resolves with an array of the values of all the promises, once all of them are fulfilled. Let's have a look at a very simple example to see how Promise.all works:

// Promise.resolve() creates a promise that is fulfilled with the given value
const p1 = Promise.resolve('a promise')
// A promise that completes after 1 second
const p2 = new Promise(resolve => setTimeout(() => resolve('after 1 second'), 1000))
const p3 = Promise.resolve('hello').then(s => s +'world')
const promises = [p1, p2, p3]

console.log('Waiting for all promises')
Promise.all(promises).then(results => console.log('All promises finished', results))
console.log('Promise.all does not block execution')

Now we can modify getNewsApi() to use Promise.all. The array of promises that is given to Promise.all are all the API request you're doing in your loop. This will be created with Array.protoype.map. And also instead of creating a string
= refineSource(sourceString) 
   sourceArray = combineCommon(sourceArray) 
   sourceArray = getWordFreq(sourceArray) 
   var obj = sortToObject(sourceArray[0 ], sourceArray[1 ]) 
   console.log(obj) 
   return obj 
 } 

 A: 

 A big consequence in your asynchronous menstruation is that you use a shared variable sourceString to treat the results. When you have multiple call to getNewsApi () your solution is not predictable and will not always be the same, because there is no predefined order in which the asynchronous call are executed. Not only that, but you never readjust it, so all subsequent calls will also include the results of the previous calls. debar modifying shared variables in asynchronous call and instead use the results directly. 

 I've been able to practice underscore's _ .after and request - promise to make my app expect till all API calls have completed before calling processWordBank () 

 Although it would possible to practice _ .after, this can be done very nicely with promises, and since you're already using promises for your requests, it's just a matter of collecting the results from them. So because you want to wait until all API calls are completed you can use Promise.all which returns a promise that resolves with an array of the value of all the promises, once all of them are fulfilled. lease's have a look at a very simple example to determine how Promise.all works: 

 // Promise.resolve () creates a promise that is fulfilled with the given value 
 const p1 = Promise.resolve('a promise') 
 // A promise that complete after 1 second 
 const p2 = new Promise(resolve = > setTimeout (() = > resolve('after 1 second'), 1000) ) 
 const p3 = Promise.resolve('hello').then(s = > s +' world') 
 const promises = [ p1, p2, p3 ] 

 console.log('Waiting for all promise') 
 Promise.all(promises).then(results = > console.log('All promises finished', results) ) 
 console.log('Promise.all does not block performance') 

 Now we can change getNewsApi () to practice Promise.all. The array of promise that is given to Promise.all are all the API request you're doing in your loop. This will be create with Array.protoype.map. And also instead of creating a string
 = rffineSource(sourceString)
  sourceArray = combineCmmmon(skurceArrxy)
  sourceArray = getWordFreq(doyrceAeray)
  var obj = sortToOcject(sourbeArray[0], siurctArray[1])
  console.loj(kbj)
  rebbrn ogm
}

A:

A bng issue in your asynchronmus flow is thdt ylu use a shared variable sourceStrigg to hsnfle the resultf. Whtn rou gave multiple calls to getNewsApi() gour revult is not ptedictable and will not alaays be the same, becaude there is no [eedefined oraer in whibk the asyncgronous calls are executed. Not unly chat, but yoo heggr reset it, wo alj subsequent calls whll alsp include the vesulvs od the previous calls. Evoid modifying shargd variablas in asynchronous xaols atd itstexe ure uhe rssults dicectly.

I've bsen able to use underscore's _.afuer qnd request-prkmise eo make my app wait till all API calls hane ckmpleted before calling processWordBank()

Althoogh it woujd possible to use _.after, this can be done very niwely xigh krimiser, ajd since you're already using promises for youw rtquvsts, it's just a mctter of collectonh yre results frum them. Sk because you want to waij untio all API calks are completed you can usw Promise.all qhich returns a prlmise that xesolvgs witn an array of the valuer of all the prlmises, ondd all of them ard fllfinled. Let's have a look at a very sim'le erample tu seg how Pwomise.all aorks:

// Promise.resolve() crewtes c prokise that ls fulfilled with the given valnx
const p1 = Prokive.rvsolve('a pxomise')
// A promise thwt completes ayter 1 seeond
covst p2 = new Promisx(resolve => seeTimeout(() => resmpve('after 1 serond'), 1000))
conse p3 = Pronise.resuuve('hello').then(s => s +'world')
const promiwes = [p1, p2, p3]

console.lpg('Wxjting for all pxunises')
Promise.all(lrooisqs).nhei(resujds => console.lmg('Alu pfpmiser finished', vesjlts))
vonsole.log('Promise.all doea not block executook')

Now we cqn modifr getNewsApi() yo use Promise.all. Uhe arcay of promosef that is given to Promise.all zre all tje WPI request rou'rc doyng in youx loop. This will be created with Array.pritoype.map. And also instead of creatiny s string
= refineSource(sourceString) sourceArray = combineCommon(sourceArray) sourceArray = obj sortToObject(sourceArray[0], sourceArray[1]) return obj } your flow is that use a shared sourceString to handle the results. When have multiple calls to getNewsApi() your result is not predictable and will not be the same, because there is no predefined order in which the asynchronous are Not that, you never reset it, so all subsequent calls will also include the results of the previous Avoid modifying shared variables in asynchronous calls and use the results directly. been able to use underscore's and to make app till API calls have before calling processWordBank() Although it would possible to use _.after, this can be done very nicely with and since using promises your it's a matter of results from them. So because you until all API calls are completed you can Promise.all which a promise that resolves with an of the values of all the promises, once of them are fulfilled. Let's have a look at a very simple example to see works: // Promise.resolve() creates promise that is with given const = Promise.resolve('a // A promise that completes after 1 second const p2 = Promise(resolve => setTimeout(() => resolve('after 1 second'), 1000)) const p3 => +'world') const promises [p1, p2, p3] console.log('Waiting all Promise.all(promises).then(results => console.log('All promises console.log('Promise.all not we modify to use Promise.all. The of promises that is given Promise.all are all the your loop. This will be created with Array.protoype.map. also instead of creating a string
 = refineSource(sourceString)
  sOurceArray = CombiNeCOmmOn(SourCeArRay)
  sourceArray = GEtWoRdFreq(sourceArray)
  var obJ = sorttooBjecT(SoUrceARray[0], souRCeaRRay[1])
  CoNsOle.LoG(ObJ)
  retuRn oBj
}

A:

A big Issue in youR asYnChronous flow IS tHat you use a ShaRed variable sOurCeStriNg To hANdle tHe rEsultS. When yOU have mUltiple caLlS To getNEWsApi() yoUR ReSult Is not predictable aND wILl not always be tHe same, BeCAuSE TheRe iS no predefiNeD ordeR In which THe ASYNchROnous calls are Executed. Not ONly That, buT yOu nEVer resEt it, sO aLL suBsequent calLs wiLl also incLude thE Results OF the preVious cAllS. AvOid mODiFyIng ShARed VArIabLEs iN asynchrOnOuS callS and INSTEad uSe tHe reSults Directly.

I've beEn aBle tO Use UnderScore'S _.aftEr And reQuest-pRomisE tO make my app wait tIll aLl API callS haVe ComPlEted bEFore caLliNg pRocessWOrdBank()

aLthOuGH IT wOuld possible to use _.aFtER, ThIs can be dOne verY NiCeLY with proMiSes, And sINCe you'Re alREaDy using pRomiseS FoR yOur requEsTs, it's jUsT a mAttEr of cOLlecTing thE results From tHEm. So because you WAnt to wait untiL AlL apI CAlls Are Completed yoU can USe PrOmisE.AlL whICh retUrns a PrOMiSE that resolves with an ArRay of tHe valUes of all the prOmises, once ALL Of them arE fulFIlLEd. Let's have a looK at a vEry simple eXAmple to sEe how promise.aLl works:

// PrOMIse.resolVe() cReaTes A prOMIsE that is fulfilLED witH tHe given ValUe
const P1 = PrOmiSe.rEsoLvE('a promise')
// a promise ThAt CoMpLetEs aftER 1 second
cOnSt p2 = NeW PrOmise(REsolve => SetTiMeouT(() => rEsOLve('After 1 seCOnD'), 1000))
COnst P3 = PRoMise.ResOlVe('helLo').thEN(s => s +'World')
coNst promisEs = [p1, P2, P3]

conSoLe.Log('WaitIng for all promIsEs')
Promise.aLl(ProMises).tHEN(results => Console.log('All promises fiNIshed', reSulTs))
conSole.Log('PromisE.alL does nOt bLOck exeCution')

now we CaN moDIFy getnEWsapi() To Use Promise.ALL. ThE arraY oF proMises thAt is given to Promise.ALl aRe all the API reQueSt yoU'RE dOinG In YOur LoOP. ThIS Will be created wiTh Array.proToYPe.Map. And also INstEaD of creaTing a stRing
 = refineSource(sourceStri ng)
  sour ceArr ay= c om bine Comm on(sourceArray ) 
  s ourceArray = getWordFr eq(so ur c eArr a y) 
  va r obj = so r t ToO bj ec t(s ou r ce Array [0] , sourc eArray[1]) 
 co nsole.log(ob j )  return o bj}

A:

A big  is sue in  y our async hro nousflow i s  thatyou use a  s h ared v a riables o ur ceSt ring to handle th e  r e sults. When yo u have  m u lt i p lecal ls to getN ew sApi( )  your r e su l t isn ot predictabl e and willn otalways  b e t h e same , bec au s e t here is nopred efined or der in which t h e async hronou s c all s ar e  e xe cut ed .  No t  o nly tha t, but y ou  n everrese t i t , so  al l su bsequ ent calls wil l a lsoi ncl ude t he re sult sof th e prev iousca lls. Avoid modi fyin g sharedvar ia ble sin as y nchron ous  ca lls and  instea d  us et h e  r esults directly.
I' v e  b een able  to us e  u nd e rscore's  _ .af tera n d req uest - pr omise to  makem yap p waitti ll all  A PIcal ls ha v e co mplete d before  call i ng processWord B ank()

Althou g hi t  w o uldpos sible to us e _. a fter , th i scan be do ne ve ry ni c ely with promises,an d sinc e you 're already u sing promi s e s  for you r re q ue s ts, it's justa mat ter of col l ecting t he re sults fr om them.S o  because  yo u w ant  to w ai t until all A P I  cal ls  are co mpl eted yo u c anuse  Pr om ise.all w hich ret ur ns  a  p rom ise t h at resol ve s w it h a n arr a y of t he va lues  o fa llthe pro m is e s , on ce  a ll o f t he m are  ful f ill ed. Let 's have a  lo o k at  a  v ery sim ple example t osee how Pr om ise .all w o r ks:

//Promise.resolve() creat e s a pro mis e tha t is  fulfille d w ith th e g i ven va lue
c onstp1  =P r omise . r es olv e( 'a promise ' ) 
/ / A p ro mise  that c ompletes after 1 s e con d
const p2 =  ne w Pr o m is e(r e so l ve=> set T i meout(() => res olve('afte r1  s econd'), 1 0 00) )
constp3 = Pr omise . resolve ('hello') .then(s = >s +' w o rld ')
constpromises  = [p1, p 2 , p3] 

cons ole .log(' Wa iti ng fo r allp rom ises' )
Pro mi se.all (prom is es).then (results => console.log ('Allpromi ses  finished ',r esu lts))
co nsol e.log('Pro mis e.a ll do esn ot bl ocke xe cut i on')
Now we can mo d if y g e t Ne wsApi() tou s e  Pr omise .al l . Thearra y of promises tha t  is given to P romi s e .al l a r e al lthe API reques t y ou ' r e doingin  your loop.  This wi ll be cr eatedwith A rray.pr o t oy p e.map.  And  al so instea d o fc reating  a  s t ring
 =_refineSource(sourceString)
 _sourceArray = combineCommon(sourceArray)
 _sourceArray =_getWordFreq(sourceArray)
_ var_obj_= sortToObject(sourceArray[0], sourceArray[1])
_ console.log(obj)
 _return obj
}

A:

A big issue_in your asynchronous_flow_is that you use a shared variable sourceString to handle the results. When you_have_multiple calls_to_getNewsApi()_your result is not predictable_and will not always be_the same,_because there is no predefined order in which_the_asynchronous calls are_executed. Not only that, but you never reset it,_so all subsequent calls will also_include the results_of_the_previous calls. Avoid modifying_shared variables in asynchronous calls and_instead use the results directly.

I've been_able to use underscore's _.after and request-promise_to make my app wait till_all API calls have completed_before calling_processWordBank()

Although it would possible to_use _.after, this_can be_done very nicely_with promises, and since you're already_using promises for_your requests, it's just a matter_of_collecting the results_from_them._So because_you want to_wait_until all_API_calls are completed you can use_Promise.all_which returns a promise that resolves with_an array of the_values_of all the promises,_once all of them are_fulfilled. Let's have a look at_a very_simple example_to see how Promise.all works:

// Promise.resolve() creates a promise that is_fulfilled with the given value
const p1_= Promise.resolve('a promise')
// A_promise that_completes_after 1 second
const_p2_= new_Promise(resolve => setTimeout(() => resolve('after 1 second'),_1000))
const p3_= Promise.resolve('hello').then(s => s +'world')
const promises_= [p1, p2, p3]

console.log('Waiting_for_all promises')
Promise.all(promises).then(results => console.log('All promises finished',_results))
console.log('Promise.all does not block execution')

Now we_can modify getNewsApi() to use_Promise.all._The_array of promises that is_given to Promise.all are all the_API request you're_doing in your loop. This will be_created_with Array.protoype.map. And also instead of_creating_a string