0

I have the following scenario:

  1. Request a token from the server
  2. Execute a request, i.e. getAllNews
  3. Parse the response of the request getAllNews
  4. Persist the parsed data
  5. Delete the requested token

and I do these 5 operations using promises:

return [self createToken].then(^(NSString *token) {
    return [self performRequestGetAllNewsUsingToken:token];
}).then(^(id responseObject) {
    return [self parseNewsResponse:responseObject];
}).then(^(NewsResponseObject *newsResponseObject) {
    return [self persistNewsFromArray:newsResponseObject.allNews inContext:self.context];
}).finally(^{
    [self deleteToken:token];
});

The problem that I face is that I cannot send parameters to finally - this token parameter is missing.

I thought about calling deleteToken as a then, immediately after [self performRequestGetAllNewsUsingToken:token], but it will only execute the operation if previous one resolved to an actual result and not an error. I should destroy the tokens regardless of what was the outcome of the request and no matter if it was executed successfully or not.

Is there a way to set a rule that If createToken is executed, then deleteToken should be called no matter what, but only after executing my normal request getAllNews?

o15a3d4l11s2
  • 3,969
  • 3
  • 29
  • 40
  • 1
    Sounds like you need the [promise disposer pattern](http://stackoverflow.com/questions/28915677/). Worked example in the reference is javascript but the problem seems to be identical to the one here. – Roamer-1888 Oct 09 '15 at 21:52
  • 1
    Also very related in JS http://stackoverflow.com/questions/28250680/how-do-i-access-previous-promise-results-in-a-then-chain – Benjamin Gruenbaum Oct 10 '15 at 19:01

1 Answers1

1

Capture the token in a closure so you have access to it in the finally clause:

NSString* token; 
return [self createToken].then(^(NSString *token_) {
    token = *token_;
    return [self performRequestGetAllNewsUsingToken:token];
}).then(^(id responseObject) {
    return [self parseNewsResponse:responseObject];
}).then(^(NewsResponseObject *newsResponseObject) {
    return [self persistNewsFromArray:newsResponseObject.allNews inContext:self.context];
}).finally(^{
    [self deleteToken:token];
});
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • I read about the disposer pattern, but could not figure out how can I apply it with my current example. Can you please give me some more information about a possible solution? This will help verify that the token is always destroyed. – o15a3d4l11s2 Oct 12 '15 at 18:06