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

Create an array of deferreds with Q.js

使用 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

我想通了 -

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