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”都应该隐含地返回一个承诺;我的想法错了吗?我应该像这样明确地返回一个承诺吗?:

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

返回的承诺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>

如果你想让一个方法返回Promise<AnyObject>,那么承诺链中的最后一个承诺必须返回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

对于您在那里的第二次尝试,您更接近,但您返回的是 unrelated 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一个中,因此现在您then的 's 将按顺序运行,以及您添加到函数返回的承诺中的任何其他内容,当它在代码中的任何其他位置被调用时。

于 2016-05-15T02:47:48.937 回答