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