Q.all doesn't call tasks

流过昼夜 提交于 2019-12-13 04:44:00

问题


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:


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


来源:https://stackoverflow.com/questions/27164227/q-all-doesnt-call-tasks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!