首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PromiseKit 3.0链

PromiseKit 3.0链
EN

Stack Overflow用户
提问于 2016-05-15 01:20:02
回答 2查看 1.2K关注 0票数 3

我试图编写一个返回承诺的函数:

代码语言:javascript
复制
func sample() -> Promise<AnyObject> {
    return Promise(1)
    .then { _ -> Void in
        debugPrint("foo")
    }.then { _ -> Void in
        debugPrint("foo")
    }
}

在最后一条语句中,我得到了一个错误:

代码语言:javascript
复制
Declared closure result 'Void' (aka '()') is incompatible with contextual type 'AnyPromise'

我的印象是,“那么”应该含蓄地回报一个承诺;我的想法是不是错了?我是否应该像这样明确地回报一个承诺?:

代码语言:javascript
复制
func sample() -> Promise<AnyObject> {
    return Promise(1)
    .then { _ -> Void in
        debugPrint("foo")
    }.then { _ -> Promise<AnyObject> in
        debugPrint("foo")
        return Promise(1)
    }
}

谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-05-15 02:56:22

then(_:)返回的承诺与闭包的返回值匹配。

代码语言:javascript
复制
func sample() -> Promise<AnyObject> {
    return Promise(1)
    .then { _ -> Void in
        debugPrint("foo")
    }.then { _ -> Void in
        debugPrint("foo")
    }
}

让我重新研究一下你的方法。

代码语言:javascript
复制
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

代码语言:javascript
复制
func sample() -> Promise<AnyObject> {
    return firstly { _ -> Void in
        debugPrint("foo")
    }.then { _ -> Void in
        debugPrint("foo")
    }.then { _ -> AnyObject in
        1
    }
}
票数 3
EN

Stack Overflow用户

发布于 2016-05-15 02:47:48

then调用返回您在它的调用中指定的任何内容,在第一个示例中返回Void

对于您的第二次尝试,您更接近了,但是您返回了一个不相关的Promise,您不得不第二次使用1来实现它。

尝试下面的代码:

代码语言:javascript
复制
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将按照顺序运行,以及在代码中其他地方调用该函数时添加到函数返回的承诺中的任何其他内容。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37233531

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档