S
S
SkyTaurus2015-08-31 22:14:27
Node.js
SkyTaurus, 2015-08-31 22:14:27

Nodejs Why is data sent early?

Good afternoon.
I have the following code (coffeescript)

Q = require("q")

class TreeObjectBuilder
  constructor:

  @data =
      userID: @userID
      is_authorized: false
      list: []
      properties: []

getProductPropertyIds: (id)->
    deferred = Q.defer();
    sql= "формирование sql"
    myResult = []

    @db.dquery(sql).then (rows) =>
      if rows.length > 0
        for row in rows
          myResult.push row.property_value_id
        console.log "myResult", id, "=>", myResult.join(",")
        deferred.resolve myResult
    
    deferred.promise;

  lastWithSQL: (sql)->
    console.log "lastWithSQL start"    
    @db.dquery(sql).then (rows) =>
        #заполнение массива array данными из базы

        #присвоение результата       
        @data.properties = array
        console.log "data3", @data
      return

  testPro: ->
    console.log "testPro start"

    

    reqs= []
    reqs.data = []
    for filter, i in @filters
      console.log filter.values
      reqs.push( @getProductPropertyIds( filter.values ) );
    
    Q.all(reqs).done =>
      sql = " формирование sql"
      console.log "------------>sql1=", sql
      return @lastWithSQL sql      

  last: ->
      console.log "call testPro"
      @testPro()
      console.log "end call testPro"

  build: ->
    promises = []    
    promises.push @last()
    Q.all promises


class TreePresenter
  tree_object: (count_properties, _ids)->
    _tree_object = new TreeObjectBuilder
    _tree_object.build().then =>
      console.log "build_then"
      console.log _tree_object.data
      
    , (error) ->
      console.error error.stack

I understand asynchronous work and got confused, the data goes to the client before it is read from the database, i.e. in the console, the output is:
call testPro
testPro start
end call testPro
lastWithSQL start
data3
build_then
I need the output sequence to be like this:
call testPro
testPro start
end call testPro
build_then
lastWithSQL start
data3
I understand that I do not wait for the lastWithSQL function to execute.
I can't figure out what's wrong.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Den Totsky, 2015-09-01
@xDen

your _tree_object.build() returns a promise, respectively, after its completion, .then => console.log "build_then" ..... i.e. build_then is executed last according to the logic of the code in this case

S
SkyTaurus, 2015-09-01
@SkyTaurus

I don’t understand something, how to fix it so that it waits for lastWithSQL to complete

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question