Chaining Promises in Coffeescript

前端 未结 3 2051
慢半拍i
慢半拍i 2021-02-02 08:56

Is there a way to chain Promises together in Coffeescript. For example, consider the following javascript code,

return $.getJSON(\'/api/post.json\')         


        
3条回答
  •  故里飘歌
    2021-02-02 09:02

    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.

提交回复
热议问题