iosswiftpromisekit

Pass value over Promise in Swift


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.


Solution

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