Is there a way to chain Promises
together in Coffeescript. For example, consider the following javascript code,
return $.getJSON('/api/post.json') .then(function(response) { // do something }) .then(function(response) { // do something }) .then(null, function(err) { // do something });
Each of the then's
is optional, and the final then
needs to be returned by the function. Currently I am writing this in coffeescript as,
promise = $.getJSON('/api/post.json') promise = promise.then (response) -> // do something promise = promise.then (response) -> // do something promise = promise.then null, (err) -> // do something return promise
Is there a better way to do this? Thanks.
Promise chaining: Promise chaining is a syntax that allows you to chain together multiple asynchronous tasks in a specific order. This is great for complex code where one asynchronous task needs to be performed after the completion of a different asynchronous task.
Introduction to the JavaScript promise chainingThe callback passed to the then() method executes once the promise is resolved. In the callback, we show the result of the promise and return a new value multiplied by two ( result*2 ).
Single-line Comments Whenever we want to comment a single line in CoffeeScript, we just need to place a hash tag before it as shown below. Every single line that follows a hash tag (#) is considered as a comment by the CoffeeScript compiler and it compiles the rest of the code in the given file except the comments.
A Promise is a JavaScript object that links producing code and consuming code.
Ezekiel shows the right way, but it doesn't need the parentheses around the functions. Just do:
$.getJSON '/api/post.json' # As of CoffeeScript 1.7, you don't need the parentheses here either. .then (response) -> # do something response # if you would not return anything, promise would be fulfilled with undefined .then (response) -> # do something undefined # necessary to prevent empty function body .then null, (err) -> # handle error
I think it's surprisingly clean. The one thing that's relatively messy is when you need to add onRejected and onFulfilled handlers at the same time.
Note: Last time I checked, this did not work in CoffeeScript Redux, but this was a few months ago.
Note 2: You need at least one line of actual code (i.e. not just a comment) in each function body for this to work. Typically, you will, so it's not a big issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With