简体   繁体   中英

Using WebDriverJS promise outside webdriver context

I am trying to use WebDriverJS promise outside Webdriver context. I have a utility that can start a proxy, set custom header, stop the proxy etc. I want to start and set custom headers before I launch the browser (before webdriver is initialized). All the methods in the utility return a promise from WebdriverJS. Here is the code,

BrowserProxy.prototype = {
'start': function () {
        var d = webdriver.promise.defer();
        someAsync(
          //here promise is either fulfilled or rejected;
          //d.reject(err) or d.fulfill();
        );
        return d;
 },
 'setHeaders': function () {
    //similar stuff like start method
 },
 'stop': function () {
    //similar stuff like start method
 }
} 

outside this file, I am doing below, however all proxy method get executed before the browser launches.

browserProxy.start();
//initialize driver
browserProxy.setHeaders();
driver.get('http://www.google.com);
browserProxy.stop();

However if I chain the calls in then methods, flow of methods is expected. I am not sure why. Can someone help?

I think the answer to your question is: Selenium "Control Flow". The control flow wraps all calls to selenium API as stated here: Control Flow .

If you want to execute "in order" (sync) some "async" task inside selenium context, you should add it to the master control flow. (note that you can create custom flows also)

Your code should look like this:

BrowserProxy.prototype = {
'start': function () {
        var flow = webdriver.promise.controlFlow();
        flow.execute(function(){
            var aPromiseToResolveWhenAsyncTaskEnds = webdriver.promise.defer();
            doAnAsyncTask().then(function(){
               aPromiseToResolveWhenAsyncTaskEnds.fulfill();
            });
            return aPromiseToResolveWhenAsyncTaskEnds.promise;
          });
 },
 'setHeaders': function () {
    //similar stuff like start method
 },
 'stop': function () {
    //similar stuff like start method
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM