Is there a way to chain Promises
together in Coffeescript. For example, consider the following javascript code,
return $.getJSON(\'/api/post.json\')
This is my personal favorite way to write promises, with a little bit extra indentation
doSomething = () -> new RSVP.Promise (resolve, reject) ->
if 1 is 1
resolve 'Success'
else
reject 'Error'
doSomething()
.then (res) ->
console.log 'Step 1 Success Handler'
, (err) ->
console.log 'Step 1 Error Handler'
.then (res) ->
console.log 'Step 2 Success Handler'
.then (res) ->
console.log 'Step 3 Success Handler'
, (err) ->
console.log 'Step 3 Error Handler'
Which compiles to:
var doSomething;
doSomething = function() {
return new RSVP.Promise(function(resolve, reject) {
if (1 === 1) {
return resolve('Success');
} else {
return reject('Error');
}
});
};
doSomething().then(function(res) {
return console.log('Step 1 Success Handler');
}, function(err) {
return console.log('Step 1 Error Handler');
}).then(function(res) {
return console.log('Step 2 Success Handler');
}).then(function(res) {
return console.log('Step 3 Success Handler');
}, function(err) {
return console.log('Step 3 Error Handler');
});
There are some instances where this works really well too:
step1Success = (res) -> console.log 'Step 1 Success Handler'
step1Error = (err) -> console.log 'Step 1 Error Handler'
step2Success = (res) -> console.log 'Step 2 Success Handler'
step3Success = (res) -> console.log 'Step 3 Success Handler'
step3Error = (err) -> console.log 'Step 3 Error Handler'
doSomething()
.then(step1Success, step1Error)
.then(step2Success)
.then(step3Success, step3Error)
Tested on coffee-script v1.6.3