Promisekit: How to execute the same function in a loop

Created on 2 Jun 2017  Â·  2Comments  Â·  Source: mxcl/PromiseKit

I want to upload multiple images asynchronously.

how can I write it using PromiseKit?

let images:[UIImage]!

self.upload(image0).then {_ in
     self.upload(image1)
}.then {_ in
     self.upload(image2)
}.then {_ in
     self.upload(image3)
}
....
.then {image9 in
     self.upload(image9)
}

or

for image in images {
....
}

Most helpful comment

when(fulfilled: images.map(upload)).then { results in
     //…
}

Or if for some reason you really want to do them serially:

var images = images
return Promise(value: ()).then { _ -> Promise<Void> in
    if let img = images.popFirst {
        return self.upload(img)
    } else {
        return Promise(value: ())
    }
}

However you should have good reason to not use when because it will be n times faster.

All 2 comments

when(fulfilled: images.map(upload)).then { results in
     //…
}

Or if for some reason you really want to do them serially:

var images = images
return Promise(value: ()).then { _ -> Promise<Void> in
    if let img = images.popFirst {
        return self.upload(img)
    } else {
        return Promise(value: ())
    }
}

However you should have good reason to not use when because it will be n times faster.

@mxcl Thank you,I really appreciate.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rlam3 picture rlam3  Â·  5Comments

Banck picture Banck  Â·  4Comments

Banck picture Banck  Â·  6Comments

ghost picture ghost  Â·  3Comments

zvonicek picture zvonicek  Â·  3Comments