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

╄→гoц情女王★ 提交于 2020-08-09 14:01:49

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/25080824/is-it-possible-to-return-from-an-outer-function-from-within-an-inner-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!