node.js - 使用 Q.js 创建延迟数组

标签 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

最佳答案

我明白了-

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

关于node.js - 使用 Q.js 创建延迟数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30110697/

相关文章:

javascript - $q.all 带有递归?

node.js - 快速请求处理程序中的 q-io/fs

node.js - 将 PGP 加密的二进制文件编码为 NodeJS 的 Base64

node.js - Facebook Messenger Bot API 发送多条消息并显示错误

javascript - 从 MongoDB 文档返回单个字段

javascript - 获取 Restangular 对象属性

node.js - 使用 Pug 和 ExpressJS 渲染列表时出错

jquery - 界定 JSONP 回调和 CoffeeScript 的范围

javascript - ember pre4 中 {{render}} 和 {{control}} 的目的是什么

promise - q.js : Is it possible to know if a promise has resolved/rejected or not