6

what's the usage of evaluateAsync and when we have to use this function and what's the benefit of using this function . in the below we see a poor documentation for this :

var webPage = require('webpage');
var page = webPage.create();
// @TODO: Finish page.evaluateJavaScript example.

any body can show a example of usage of evaluateAsync in phantomjs

MOB
  • 853
  • 2
  • 13
  • 28

1 Answers1

10

This function allows you to execute any JavaScript code like the evaluate API function. But it will evaluate your code asynchronous. It means:

  • Current execution context will not be blocked.
  • It will not return any result.

Let's say you want execute some long-running JavaScript code, but you don't interested in its result. If you will use evaluate, your current execution context will be blocked.

The documentation for evaluateAsync is a bit wrong. The correct signature for evaluateAsync is: evaluateAsync(function, ms, args), where:

  • function - the function to evaluate
  • ms - time to wait before execution
  • args - function arguments

Example:

evaluateAsync(function() {
   console.log('Hi! I\'m evaluateAsync call!');
}, 1000);

Using in the real world:

  • You want to capture some asynchronous events.
  • Unit testing! AFAIK, PhantomJS runners use evaluateAsync to run unit tests.
Vitaly Slobodin
  • 1,359
  • 12
  • 10
  • i want get a string from document dom every 1 sec and send it's answer to other function... what is better for me ? evaluateAsync or evaluate – MOB Mar 18 '14 at 12:53
  • 1
    You'd better use `evaluate` with `setInterval`, something like this: `setInterval(function() { myText = page.evaluate(function() { return dom.text; } )});` – Vitaly Slobodin Mar 18 '14 at 12:56
  • id do that .. but after 20min phantomjs crash and show below error : PhantomJS has crashed. Please read the crash reporting guide at... – MOB Mar 18 '14 at 12:57
  • If you see a crash, follow this guide about crash reporting: http://phantomjs.org/crash-reporting.html And we'll take a look into this. – Vitaly Slobodin Mar 18 '14 at 12:58
  • 1
    The documentation should really be fixed...the only reason I got my code working is because I stumbled upon this SO post. – ThisSuitIsBlackNot Nov 10 '14 at 22:56