I'm using PromiseKit with Swift, which has been very handy so far. One of the functions they provide is when()
, which allows you to have an array of any number of promises and execute something only once ALL of them have completed.
However, the promises in the array are executed in parallel. I have not found any function that allows me to execute them sequentially. I've tried to write a recursive function of my own, but it doesn't appear to be executing the promises in the order in which they are in the array, and I get the occasional "Promise deallocated" bug. Please help!
static func executeSequentially(promises: [Promise<Void>]) -> Promise<Void> {
return Promise<Void> { fulfil, reject in
var mutablePromises = promises
if mutablePromises.count > 0 {
mutablePromises.first!
.then { _ -> Promise<Void> in
print("DEBUG: \(mutablePromises.count) promises in promise array.")
mutablePromises.remove(at: 0)
return executeSequentially(promises: mutablePromises)
}.catch { error in
print("DEBUG: Promise chain rejected.")
reject(error)
}
} else {
print("DEBUG: Promise chain fulfilled.")
fulfil(())
}
}
}