30

有没有办法Promises在 Coffeescript 中链接在一起。例如,考虑以下 javascript 代码,

return $.getJSON('/api/post.json')
  .then(function(response) {
    // do something
  })
  .then(function(response) {
    // do something
  })
  .then(null, function(err) {
    // do something
  });

每个then's都是可选的,最终then需要由函数返回。目前我正在用咖啡脚本写这个,

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

有一个更好的方法吗?谢谢。

4

3 回答 3

44

Ezekiel 显示了正确的方法,但它不需要函数周围的括号。做就是了:

$.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

我觉得它出奇的干净。相对混乱的一件事是当您需要同时添加 onRejected 和 onFulfilled 处理程序时。

注意:上次我检查时,这在 CoffeeScript Redux 中不起作用,但这是几个月前的事了。

注意 2:每个函数体中至少需要一行实际代码(即不仅仅是注释)才能使其工作。通常,你会,所以这不是一个大问题。

于 2013-07-07T17:16:28.343 回答
14

这是我个人最喜欢的写 promise 的方式,有一点额外的缩进

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'

编译为:

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');
});

在某些情况下,这也非常有效:

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)

在咖啡脚本 v1.6.3 上测试

于 2013-12-08T03:08:52.157 回答
4

这可能是你会做的最好的:

$.getJSON('/api/post.json')
    .then( (response) ->
      # do something
    ).then( (response) ->
      # do something
    ).then null, (err) ->
      # do something

请注意参数周围的括号then()。没有什么惊天动地的,但希望这会有所帮助。

于 2013-07-07T09:55:32.317 回答