使用Q.js创建一个延迟数组

时间:2015-05-07 20:05:56

标签: node.js coffeescript q

使用Q和请求模块,我试图将动态数量的延迟推送到数组中,因此我可以稍后调用Q.all。我在周围和下面阅读的内容尽可能接近,但它无法正常工作。

我认为我得到了Q.all部分,但是我应该如何将每个延迟存储在数组中的是我被绊倒的地方。

_ = require 'underscore'
request = require 'request'
Q = require 'q'


class Github

  ## Filter issues by "important Label"
  getIssues: (callback) ->

    options ...

    request options, (err, resp, body) =>

      issues = _.filter JSON.parse(body), (issue) ->
         ...

      ## I'm attempting to store my promises in this `deferreds`
      deferreds = @getPulls issues


      ## to test I'm getting something, and I do
      setTimeout ( => console.log @pulls.length ), 2500

      ## but this gives me 0
      Q.all(deferreds).then( (a,b) =>
        console.log 'Q all', @pulls.length
      )


  # Get PR info for important issues
  getPulls: (issues) ->

    deferreds = []
    @pulls = []

    for issue in issues

      options = ...
      deferred = Q.defer()

      deferreds.push request options, (err, resp, body) =>
        @pulls.push JSON.parse body
        deferred.resolve(JSON.parse(body))

        return deferred.promise


    return deferreds



module.exports = Github

1 个答案:

答案 0 :(得分:0)

我想出来了 -

class Github

  pulls = []

  getIssues: (callback) ->    

    options = ...
    request options, (err, resp, body) =>

      issues = _.filter JSON.parse(body), (issue) ->
        ....

      @pulls = []
      deferreds = []

      for issue in issues
        d = @makeDeferred issue
        deferreds.push d

      Q.all(deferreds).then( (a,b) =>
        console.log 'Q all done', @pulls.length
      )


  makeDeferred: (issue) ->
    deferred = Q.defer()

    options = ...

    request options, (err, resp, body) =>
      @pulls.push JSON.parse(body)
      deferred.resolve()

    deferred.promise  


module.exports = Github