使用Q和request模块,我试图将动态数量的deferreds推送到数组中,以便以后可以在它们上调用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

10-05 19:24