是否可以从内部函数中从外部函数返回? [英] Is it possible to return from an outer function from within an inner function?

查看:108
本文介绍了是否可以从内部函数中从外部函数返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从内部函数中跳出外部函数。

I would like to jump out of an outer function from inside an inner function.

something = true

outer: (next)-> 
    @inner (err)-> 
        if err?
            next err 
            #jump out of outer function here

    console.log 'still in outer'

inner: (next)-> 
    next new Error 'oops' if @something is true

代码在coffeescript中,但是欢迎使用javascript答案。

The code is in coffeescript but javascript answers are welcome.

更新

感谢您的快速答复-因此如何使用 @inner 函数的返回值?

Thanks for the quick replies - so how about using the return value of the @inner function? Is there a generally accepted pattern for this kind of thing?

something = true

outer: (next)-> 
    return unless @inner (err)-> next err if err
    console.log 'still in outer'

inner: (next)-> 
    if @something is true
        next new Error 'oops'
        return false
    return true


推荐答案

如果您要立即退出外部的原因是原因如果发生了异常情况(错误),则可以引发异常。如果外部没有抓住它,外部将被终止(外部的调用方,依此类推,直到某些东西捕获到异常或JS引擎本身捕获了。)

If the reason you want to immediately exit outer is that an exceptional condition occurred (an error), you can throw an exception. If outer doesn't catch it, outer will be terminated (as will outer's caller, and so on, until something either catches the exception or the JS engine itself does).

对于 normal 程序流,但是,在JavaScript和可转换为它的各种语言中,我们不在正常的程序流中使用异常(特别是因为它们很昂贵)。在这种情况下,没有,被调用函数无法终止其调用方;

For normal program flow, though, in JavaScript and the various languages that transpile into it, we don't use exceptions for normal program flow (not least because they're expensive). For those cases, no, there's no way for a called function to terminate its caller; it has to either return a value that caller uses to know to exit, or set a value on a variable that's in scope for both of them.

在这里,您的示例已更新为使用内部的返回值,这是执行此操作的最正常方法:

Here's your example updated to use inner's return value, which would be the most normal way to do this:

something = true

outer: (next)-> 
    stop = @inner (err)-> 
        if err?
            next err 
            #jump out of outer function here

    if stop
      return
    console.log 'still in outer'

inner: (next)-> 
    next new Error 'oops' if @something is true
    if someCondition
      return true

这里是您的示例更新为使用它们都关闭的变量:

Here's your example updated to use a variable they both close over:

something = true

stop = false

outer: (next)-> 
    @inner (err)-> 
        if err?
            next err 
            #jump out of outer function here

    if stop
      return
    console.log 'still in outer'

inner: (next)-> 
    next new Error 'oops' if @something is true
    if someCondition
      stop = true

(请原谅我的CoffeeScript,我不使用它。)

这篇关于是否可以从内部函数中从外部函数返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆