1

I'm trying to chain a number of promises that need to be resolved before returning.

In my case, for each element of databaseResult I need to fetch some data with a method that returns a promise.

Once I've fetched the data for every single element of the array I need to return to the calling method.

var toReturn = [MatchModel]()
//get my array of data
let databaseResults = MatchDatabaseManager.getMatchList();

    //not sure what I'm doing
    var promise = dispatch_promise{ 0 }
    if(databaseResults.count > 0) {
        return Promise { fulfill, reject in

            for index in 0..<databaseResults.count {
                print(index)
                promise = promise.then { y -> Promise<Int> in
                    //Fetch the data I need ...

                  DataProvider.getUserProfileWithUserId(
                  (databaseResults[y].partnerUserProfile?.userId)!)
                  .then {(model) in {
                  //and use it to create the data I need to return
                        toReturn.append(MatchModel(realmModel:            
                         databaseResults[y], partnerProfile: model))

                        }
                    }

                    return dispatch_promise { index }
                }
            }
            //Once all the promises are fulfilled, toReturn contains the data I need and I can return it
            promise.then{ x in {
                fulfill(toReturn)
                }
            }
        }
    }

If I run this I get

 PromiseKit: Pending Promise deallocated! This is usually a bug

I have very little experience with PromiseKit and documentation / exaples are scarce, so I have no idea what I'm missing here.

Jack
  • 171
  • 2
  • 16

2 Answers2

2

After asking the library developer for some help, I found out one must use "when" to wait for a series of promises to be completed. The solution to the problem then becomes

return when(databaseResults.map{ (dbresult : MatchRealmModel) in
            return DataProvider.getUserProfileWithUserId((dbresult.partnerUserProfile?.userId)!).then { model in
                return MatchModel(realmModel: dbresult, partnerProfile: model)
            }
            })
Jack
  • 171
  • 2
  • 16
2

I also found that a when() call with an empty array as the parameter can cause this issue.

Zane Claes
  • 14,732
  • 15
  • 74
  • 131