How does CoffeeScript handle Asynchronous Calls?

2019-07-20 10:31发布

Current Asynchronous JavaScript calls require us to use a Callback function. This can lead to "rabbit hole" code when you need to make a 2nd Ajax call based on data returned in a 1st Ajax call.

There have been attempts to make Asynchronous JavaScript calls without the use of Callbacks. Google, Narative.js. The goal being more manageable and readable code.

My question is, How does CoffeeScript handle Asynchronous JavaScript calls like Ajax? Are callbacks required or can Asynchronous calls be made without callbacks?

4条回答
Melony?
2楼-- · 2019-07-20 10:43

You may want to adopt https://github.com/mirek/node-flat-flow approach to make call chain flat. It works very well with coffeescript.

查看更多
乱世女痞
3楼-- · 2019-07-20 10:51

CoffeeScript doesn't offer any particular features geared toward asynchronicity, because this would necessarily cause a large gap between CoffeeScript code and the JavaScript output. See the discussion about the proposed defer syntax:

https://github.com/jashkenas/coffee-script/issues/350

So, if you use CoffeeScript, you should deal with asynchronous behavior using the same idioms and libraries as in JavaScript. The difference is that your callbacks will be written as -> ... rather than function() {...}.

查看更多
聊天终结者
4楼-- · 2019-07-20 10:52

you could use jquery $.when (not coffee script specific) to make things more clear.

var firstCall = $.get 'stuff.json'
$.when(firstCall).then #make second call
查看更多
冷血范
5楼-- · 2019-07-20 10:54

Coffeescript is a language that some people think is clearer, more concise, and easier to write and read than Javascript. Coffeescript compiles to Javascript, which then runs on a Javascript virtual machine. At the end of the day, Coffeescript can only do what Javascript is capable of doing.

How does CoffeeScript handle Asynchronous Calls?

Like Javascript. If you want to use callbacks, use callbacks. If you want to use Narative.js, use that. If you want to use Jquery, use that.

查看更多
登录 后发表回答