3

私は約束を返す関数を書こうとしています:

func sample() -> Promise<AnyObject> {
    return Promise(1)
    .then { _ -> Void in
        debugPrint("foo")
    }.then { _ -> Void in
        debugPrint("foo")
    }
}

最後の then ステートメントでエラーが発生します。

Declared closure result 'Void' (aka '()') is incompatible with contextual type 'AnyPromise'

私は、'then' は黙示的にプロミスを返さなければならないという印象を受けました。私の考えは間違っていますか?このように明示的に promise を返す必要がありますか?:

func sample() -> Promise<AnyObject> {
    return Promise(1)
    .then { _ -> Void in
        debugPrint("foo")
    }.then { _ -> Promise<AnyObject> in
        debugPrint("foo")
        return Promise(1)
    }
}

ありがとう

4

2 に答える 2

3

によって返される promise はthen(_:)、クロージャの戻り値と一致します。

func sample() -> Promise<AnyObject> {
    return Promise(1)
    .then { _ -> Void in
        debugPrint("foo")
    }.then { _ -> Void in
        debugPrint("foo")
    }
}

あなたの方法を作り直させてください。

func sample() -> Promise<AnyObject> {
    let p1: Promise<AnyObject> = Promise(1)
    let p2: Promise<Void> = p1.then { _ -> Void in
        debugPrint("foo")
    }
    let p3: Promise<Void> = p2.then { _ -> Void in
        debugPrint("foo")
    }
    return p3
}

Promise<AnyObject>の期待される戻り値の型がの実際の戻り値の型と一致しないことがわかりますPromise<Void>

メソッドを return にしたい場合Promise<AnyObject>は、promise チェーンの最後の promise を return にする必要がありAnyObjectます。

func sample() -> Promise<AnyObject> {
    return firstly { _ -> Void in
        debugPrint("foo")
    }.then { _ -> Void in
        debugPrint("foo")
    }.then { _ -> AnyObject in
        1
    }
}
于 2016-05-15T02:56:22.607 に答える
2

最初の例では、then呼び出しは呼び出しで指定したものを返しますVoid

そこでの 2 回目の試行では、より近づいていますが、関係のない を返してPromiseいます1

代わりに次のコードを試してください。

func sample() -> Promise<AnyObject> {
    return Promise<AnyObject> { fulfill, reject in
        return Promise<AnyObject>(1)
        .then { _ -> Void in
            debugPrint("foo")
        }.then { _ -> Void in
            debugPrint("foo")
        }
    }
}

Promiseこれにより、2 番目が 1番目に組み込まthenれるため、コード内の他の場所で関数が呼び出されたときに、関数によって返される promise に追加する他のものと同様に、 が順番に実行されます。

于 2016-05-15T02:47:48.937 に答える