Pass value over Promise in Swift

142 Views Asked by At

I have a Promise chain like this

firstly {
   Network.shared.getInfo()
}
.then { info in
   Network.shared.getUserDetail(info)
}
.then { detail in
   Network.shared.getAddOn(detail)
}
.done { addOn in
 //do stuff with addOn
}
.catch { error in 
}

and I need to have all values (info, detail and addOn) in the .done Promise block. Is there a way to extend visibility or pass values throught Promise ?

I can't use when(fulfilled: []) because each value depends from the previous one.

Thanks.

2

There are 2 best solutions below

0
Dávid Pásztor On BEST ANSWER

You could propagate the inputs from your previous promise to the next promises by wrapping the new value and the previous one(s) in a tuple.

firstly {
   Network.shared.getInfo()
}
.then { info in
   (info, Network.shared.getUserDetail(info))
}
.then { info, detail in
   (info, detail, Network.shared.getAddOn(detail))
}
.done { info, detail, addOn in
 //do stuff with addOn
}
.catch { error in 
}

Alternatively, you could change your methods to return tuples themselves or to return a type which wraps the input arg and the newly generated return value.

So for instance change Network.shared.getUserDetail(info) from returning just UserDetail to returning (UserInfo, UserDetail).

1
Pierre Janineh On

You need to create variables to assign your values to, Ex:

var info: Info
var detail: Detail
var addOn: AddOn

firstly {
   Network.shared.getInfo()
}
.then { info in
   self.info = info
   Network.shared.getUserDetail(info)
}
.then { detail in
   self.detail = detail
   Network.shared.getAddOn(detail)
}
.done { addOn in
   self.addOn = addOn

   //do stuff with addOn
}
.catch { error in 
}