Q.all不调用任务 [英] Q.all doesn't call tasks
问题描述
所以我有这个CoffeeScript(简化为专注于真正的问题)
So I have this CoffeeScript (simplified to focus on the real problem)
Q = require 'q'
events = require 'events'
class SomeObj extends events.EventEmitter
constructor: () ->
setTimeout () =>
@emit 'done'
, 3000
class SomeObj2 extends events.EventEmitter
constructor: () ->
setTimeout () =>
@emit 'done'
, 50000
class Main
someObj1: null
someObj2: null
constructor: () ->
Q.all([
=> @task1(),
=> @task2()])
.then (results)->
console.log 'results'
console.log results
.catch((error)->
console.log 'error'
console.log error
)
task1: () ->
console.log 'task1 started'
defer = Q.defer()
@someObj = new SomeObj()
@someObj.on 'done', (err, data) =>
console.log 'task1 done'
defer.resolve data
return defer.promise
task2: () ->
console.log 'task2 started'
defer = Q.defer()
@someObj2 = new SomeObj2()
@someObj2.on 'done', (err, data) =>
console.log 'task2 done'
defer.resolve data
return defer.promise
main = new Main()
输出为:
results
[ [Function], [Function] ]
Main :: constructor
,回调 @ task1
和 @ task2
似乎没有得到调用。所以要确定这一点,我已经添加 console.log
在他们的顶部。
In Main::constructor
, the callbacks @task1
and @task2
doesn't seem to get called. So to be sure about this, I've had added console.log
at the top of both of them. And as they don't get printed out, I can be sure they're not called.
为了测试,我替换了这个块
For testing purposes, I replaced this block
constructor: () ->
Q.all([
=> @task1(),
=> @task2()])
.then (results)->
console.log 'results'
console.log results
.catch((error)->
console.log 'error'
console.log error
)
此区块
constructor: () ->
Q.fcall () => @task1()
.then () => @task2()
.then (results)->
console.log 'results'
console.log results
.catch((error)->
console.log 'error'
console.log error
)
这实际上是预期的,但它不是我想要的。目标是并行启动task1和2。
and this actually works as espected, but it's not what I want. The goal is to start task1 and 2 in parallel.
注意:在任务中,我想能够使用 @
主要
Side note: Inside the tasks, I would like to be able to use @
for member variables of Main
有什么问题?
推荐答案
Q.all
helper 期望一个数组或promise来解析,而不是一个函数数组。这意味着如果你想使用 Q.all
,你应该自己调用所有的任务。
Q.all
helper expects an array or promises to resolve, not an array of functions. It means that you should call all your tasks yourself if you want to use Q.all
.
,删除匿名函数包装将会做到:
In your example, removing anonymous function wrappings will do the trick:
constructor: () ->
Q.all([
@task1()
@task2()
]).then (results) ->
// Success
.catch (error) ->
// Error
这篇关于Q.all不调用任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!