简体   繁体   中英

How to avoid this return in nested coffeescript?

Here's what I want to see:

kango.invokeAsync('kango.storage.getItem', 'item1', function(returned1) {
    kango.invokeAsync('kango.storage.getItem', 'item2', function(returned2) {
        alert(returned1 + returned2);
    });
});

Here's what I wrote in coffeescript:

kango.invokeAsync 'kango.storage.getItem', 'item1', (returned1) ->

  kango.invokeAsync 'kango.storage.getItem', 'item2', (returned2) ->

    alert returned1 + returned2

The problem here is that no matter what, coffeescript is making the function ()-> return something. In that case, the last statement is being returned for some reason.

If I were to place a second alert in the nested function with returned2, it would return instead of the first one:

kango.invokeAsync('kango.storage.getItem', 'item1', function(returned1) {
    kango.invokeAsync('kango.storage.getItem', 'item2', function(returned2) {
      alert(returned1 + returned2);
      return alert('something');
    });

How to have it avoid doing the return?

If you don't want a function to return something then just say return :

kango.invokeAsync 'kango.storage.getItem', 'item1', (returned1) ->
  kango.invokeAsync 'kango.storage.getItem', 'item2', (returned2) ->
    alert returned1 + returned2
    return

return behaves the same in CoffeeScript as it does in JavaScript so you can say return if you don't want any particular return value.

If you don't specify an explicit return value using return , a CoffeeScript function will return the value of the last expression so your CoffeeScript is equivalent to:

kango.invokeAsync 'kango.storage.getItem', 'item1', (returned1) ->
  kango.invokeAsync 'kango.storage.getItem', 'item2', (returned2) ->
    return alert returned1 + returned2

The result will be the same though, alert doesn't return anything so:

f = ->
    alert 'x'
    return
x = f()

will give undefined in x but so will this:

f = -> alert 'x'
x = f()

In coffeescript a function always returns the final statement. You can explicitly make a function return undefined by making that the final statement.

kango.invokeAsync 'kango.storage.getItem', 'item1', (returned1) ->

  kango.invokeAsync 'kango.storage.getItem', 'item2', (returned2) ->

    alert returned1 + returned2
    `undefined`

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