ios - Swift execute asynchronous tasks in order -


i have few asynchronous, network tasks need perform on app. let's have 3 resources need fetch server, call them a, b, , c. let's have finish fetching resource a first before fetching either b or c. sometimes, i'd want fetch b first, other times c first.

right now, have long-chained closure so:

func fetcha() {   afnetworking.get(completionhandler: {     self.fetchb()     self.fetchc()   }) } 

this works now, obvious limitation i've hard-coded order of execution completion handler of fetcha. now, want fetchc after fetchb has finished in completion handler, i'd have go change implementation fetchb...

essentially, i'd know if there's magic way like:

let orderedasync = [fetcha, fetchb, fetchc] orderedasync.executeinorder() 

where fetcha, fetchb, , fetchc async functions, fetchb won't execute until fetcha has finished , on. thanks!

you can use serial dispatchqueue mixed dispatchgroup.enter(), dispatchgroup.leave() , dispatchgroup.modify() ensure 1 execution block run @ time.

let serialqueue = dispatchqueue(label: "serialqueue") let dispatchgroup = dispatchgroup() group.enter() serialqueue.async{  //call whenever need add new work item queue     fetcha{         //in completion handler call         group.leave()     } } serialqueue.async{     group.wait()     group.enter()     fetchb{         //in completion handler call         group.leave()     } } serialqueue.async{     group.wait()     group.enter()     fetchc{         group.leave()     } } 

or if allowed use 3rd party library, use promisekit, makes handling , chaining async methods way easier gcd provides. see official github page more info. can wrap async method completion handler in promise , chain them this:

promise.wrap(fetcha(completion:$0)).then{ valuea->promise<typeofvalueb> in     return promise.wrap(fetchb(completion:$0) }.then{ valueb in  }.catch{ error in     //handle error } 

also, errors propagated through promises.


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -