Promisekit: Known which promises is failed in when?

Created on 24 Sep 2018  Â·  4Comments  Â·  Source: mxcl/PromiseKit

Hello!
Sorry, but I haven't saw answer:
I have, for example 2 promises and want to do after both are done. So I'm using when, but if , for example, first promise was failed, but the second will be done I want to do something.
So the code is simple:

when(fulfilled: firstPromise, secondPromise)
            .done { (firstPromiseResult, secondPromiseResults) in

        }
            .catch { (error) in
        }

but if firstPromis will be failed, .catch block will be executed. So how can I know which promise was failed and get result of the second promise, if it done?
Thanks!

Most helpful comment

Indeed! Thanks @bellebethcooper, sorry I didn't get back to you @Banck, was abroad.

when(resolved:) is one option. The other is to get off the promise you care more about:

let p1 = foo().get {
    // do something with $0
}
let p2 = bar()

when(fulfilled: p1, p2).done {
     // p1’s get will have already been executed, provided p1 succeeded
}.catch {
     // p1 or p2 failed
}

With when(resolved:) you would do something like:

when(resolved: [p1, p2]).done { results in
    if p1.isRejected {  // alternatively use `results[0]` which is of type `Result<T>`
         // special code
    }
    //…
}

Both are valid, it just depends what you intended. when(resolved:) can be fiddly, partly because it requires all promises to have the same type, which is due to Swift’s generics system being basic in this area.

All 4 comments

I’m not available to comment right now, but I’m pretty sure our documentation shows several ways to do this.

Someone else can probably help with a better answer, but I think you might want to switch from using when(fulfilled:) to when(resolved:). The info in the Getting Started guide under the heading "when Variants" says:

when(resolved:) waits even if one or more of its component promises fails.

Indeed! Thanks @bellebethcooper, sorry I didn't get back to you @Banck, was abroad.

when(resolved:) is one option. The other is to get off the promise you care more about:

let p1 = foo().get {
    // do something with $0
}
let p2 = bar()

when(fulfilled: p1, p2).done {
     // p1’s get will have already been executed, provided p1 succeeded
}.catch {
     // p1 or p2 failed
}

With when(resolved:) you would do something like:

when(resolved: [p1, p2]).done { results in
    if p1.isRejected {  // alternatively use `results[0]` which is of type `Result<T>`
         // special code
    }
    //…
}

Both are valid, it just depends what you intended. when(resolved:) can be fiddly, partly because it requires all promises to have the same type, which is due to Swift’s generics system being basic in this area.

Thanks a lot, guys!

Was this page helpful?
0 / 5 - 0 ratings