Search code examples
swiftpromisekit

PromiseKit firstly around code, not function call


I don't want to write a separate function to return a Promise in my firstly call. I just want to write this:

firstly
{
    return Promise<Bool>
    { inSeal in
        var isOrderHistory = false
        let importTester = CSVImporter<String>(url: url)
        importTester?.startImportingRecords(structure:
            { (inFieldNames) in
                if inFieldNames[2] == "Payment Instrument Type"
                {
                    isOrderHistory = true
                }
            }, recordMapper: { (inRecords) -> String in
                return ""   //  Don't care
            }).onFinish
            { (inItems) in
                inSeal.resolve(isOrderHistory)
            }
    }
}
.then
{ inIsOrderHistory in
    if inIsOrderHistory -> Void
    {
    }
    else
    {
...

But I'm getting something wrong. ImportMainWindowController.swift:51:5: Ambiguous reference to member 'firstly(execute:)'

None of the example code or docs seems to cover this (what I thought was a) basic use case. In the code above, the CSVImporter operates on a background queue and calls the methods asynchronously (although in order).

I can't figure out what the full type specification should be for Promise or firstly, or what.


Solution

  • According to my understanding, since you are using then in the promise chain, it is also meant to return a promise and hence you are getting this error. If you intend not to return promise from your next step, you can directly use done after firstly.

    Use below chain if you want to return Promise from then

    firstly {
         Promise<Bool> { seal in
            print("hello")
            seal.fulfill(true)
         }
    }.then { (response) in
        Promise<Bool> { seal in
                print(response)
                seal.fulfill(true)
        }
    }.done { _ in
        print("done")
    }.catch { (error) in
            print(error)
    }
    

    If you do not want to return Promise from then, you can use chain like below.

    firstly {
                Promise<Bool> { seal in
                    print("hello")
                    seal.fulfill(true)
                }
            }.done { _ in
                    print("done")
            }.catch { (error) in
                    print(error)
            }
    

    I hope it helped.

    Updated:

    In case you do not want to return anything and then mandates to return a Promise, you can return Promise<Void> like below.

    firstly {
        Promise<Bool> { seal in
            print("hello")
            seal.fulfill(true)
        }
    }.then { (response) -> Promise<Void> in
                print(response)
                return Promise()
    }.done { _ in
            print("done")
    }.catch { (error) in
            print(error)
    }