Q.all doesn't call tasks

2019-08-20 16:50发布

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()

The output is:

results
[ [Function], [Function] ]

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
    )

by this block

  constructor: () ->
    Q.fcall () => @task1()
    .then ()  => @task2()
    .then (results)->
      console.log 'results'
      console.log results
    .catch((error)->
      console.log 'error'
      console.log error
    )

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

What's wrong?

1条回答
等我变得足够好
2楼-- · 2019-08-20 17:05

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
查看更多
登录 后发表回答