o15a3d4l11s2
o15a3d4l11s2

Reputation: 4059

Chaining of promises in PromiseKit

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?

Upvotes: 0

Views: 805

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276306

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];
});

Upvotes: 1

Related Questions