1

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.

Fry
  • 6,235
  • 8
  • 54
  • 93

2 Answers2

2

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).

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
1

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 
}
Pierre Janineh
  • 394
  • 2
  • 13
  • This won't actually work, since you need to give default values to all properties. So you'd need to make the properties `Optional`, but then you'd need to unwrap them in `done`. – Dávid Pásztor Apr 03 '23 at 14:19