当我需要执行调用程序暂停/等待时,如何使用promise.then()?

时间:2014-05-22 22:15:45

标签: javascript jquery coffeescript

我对自己的承诺感到困惑。

我有一个名为validateCurrentStep的现有函数,它是在多步骤表单中点击的。

突然,在其中一个表单元素上的keypress上发生了一些AJAX验证,这意味着在调用validateCurrentStep时验证可能无法完成。

validateCurrentStep: ->
    $step = @getCurrentStep()
    if valid()
        return true
    return false

我想提取一个promises列表并暂停此函数,直到返回值。

validateCurrentStep: ->
    $step = @getCurrentStep()
    $promises = $step.data('promises')

    # how do I delay wait until the `then` is complete?
    $.when($promises).then =>
        if valid()
            return true
        return false

1 个答案:

答案 0 :(得分:1)

$.when确实需要多个参数,而不是一组承诺。在coffeescript中,使用

$.when $promises...

将返回所有promises已成功的另一个承诺。你不能真正“暂停”这个功能,但是你可以稍后调用回调。

validateCurrentStep: ->
    $step = @getCurrentStep()
    $promises = $step.data('promises')

    # notice the implicit return values in CS
    $.when($promises...).then ->
        valid()

validateCurrentStep().then (isValid) ->
    # do what you need to do