Tim Scott
Tim Scott

Reputation: 15205

CasperJS evaluate returns a function

How do I get evaluate to return the return of the callback?

ary = @evaluate ->
  [1, 2, 3]
@echo "LENGTH: #{ary.length}"
@echo "TYPE: #{ary.constructor}"

Outputs:

LENGTH: undefined
TYPE: function

Then it outputs the body of the function, which is some part of Casper.

Based on samples like this one I'm expecting ary to be my array. What am I missing here?

UPDATE:

By the way, this works:

ary = eval @evaluate ->
  '[1, 2, 3]'
@echo "LENGTH: #{ary.length}"
@echo "TYPE: #{ary.constructor}"

Outputs:

LENGTH: 3
TYPE: Array

Do I have to marshal output from evaluate as string (or other primitives)? That's not what the samples show.

UPDATE #2

I'm using PhantomJS 1.9.1 which might have something to do with it since I cannot replicate the problem after downgrading to 1.9.0.

Upvotes: 0

Views: 552

Answers (1)

hexid
hexid

Reputation: 3811

I'm able to use the following code on CasperJS 1.1-dev and PhantomJS 1.9.1

ary = []
casper.then ->
  ary = @evaluate ->
    [1, 2, 3]

casper.then ->
  @echo "LENGTH: #{ary.length}"
  @echo "TYPE: #{ary.constructor}"
  require('utils').dump(ary)

This produces the following output:

LENGTH: 3
TYPE: function Array() {
    [native code]
}
[
    1,
    2,
    3
]

The problem you are facing is most likely due to

@echo "LENGTH: #{ary.length}"
@echo "TYPE: #{ary.constructor}"

being printed before the evaluate has finished executing.

By wrapping both of these in Casper.then, you can avoid running into these asynchronous issues.

Upvotes: 3

Related Questions