leafo / moonscript

:crescent_moon: A language that compiles to Lua
https://moonscript.org
3.18k stars 190 forks source link

Would you consider implementing backcalls? #314

Closed ceremcem closed 7 years ago

ceremcem commented 7 years ago

Backcalls are very useful when it comes to prevent callback hell: http://livescript.net/#backcalls

In addition, it makes feel like you write a synchronous code:

sleep = (ms, f) -> set-timeout f, ms 

cnt = 5
console.log 'hello'
<- sleep 2000ms 
<- :lo(op) -> 
  console.log "hey #{cnt}"
  <- sleep 1000ms # think this is an asynchronous DB operation
  cnt--
  return op! unless cnt > 0
  lo(op)
console.log "this will be printed lastly"

Which will then compiled to:

var sleep, cnt;
sleep = function(ms, f){
  return setTimeout(f, ms);
};
cnt = 5;
console.log('hello');
sleep(2000, function(){
  return function lo(op){
    console.log("hey " + cnt);
    return sleep(1000, function(){
      cnt--;
      if (!(cnt > 0)) {
        return op();
      }
      return lo(op);
    });
  }(function(){
    return console.log("this will be printed lastly");
  });
});
leafo commented 7 years ago

have you looked into coroutines? http://leafo.net/posts/itchio-and-coroutines.html

ceremcem commented 7 years ago

Well, as a gevent fan, I agree that there is no need for extensive callbacks :+1: