简体   繁体   中英

Is it possible to return from an outer function from within an inner function?

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

The code is in coffeescript but javascript answers are welcome.

Update

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

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).

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

(Please excuse my CoffeeScript, I don't use it.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM