简体   繁体   中英

How to chain promises through a callback in JavaScript?

I am currently writing an integration test with Mocha, Chai, and WebdriverIO. The WebdriverIO syntax requires a chain of promises to navigate through the browser, an example of which is below:

it('sign in and out test', function() {
  return client
    .url(Page.url)
    .pause(20000)
    .waitForVisible(HomePage.signInDropdown, 10000)
    .click(HomePage.signInDropdown)
}

This leads to long blocks of code with every step laid out explicitly. Since some of the steps (such as logging in and logging out) are used frequently throughout different tests, I want to modularize those snippets of code through callbacks. However, the following syntax, which works without a nested callback, fails:

function myCallback(){
  console.log('This is where I''d add promises');
}

it('sign in and out test',function() {
  return client
    .url(Page.url)
    .pause(20000)
    .then(function() {
      myCallback();
    }
    .waitForVisible(HomePage.signInDropdown, 10000)
    .click(HomePage.signInDropdown)
}

The following different syntax in the callback also fails:

function myCallback(){
  return client
    .url(Page.url)
  console.log('This is a callback using return');
}

Given that promises are mostly intended to replace callbacks, is it possible in this special case to continue the promise chain through a callback?

myCallback() is not return ed from .then() .

.then(function() {
  // `return` value from `myallback()`
  return myCallback();
})

after logout promise resolve we need to do other works in chain.

Please check this,

function myCallback(){
  return client
    .url(Page.url)
}

it('sign in and out test',function() {
  return client
    .url(Page.url)
    .pause(20000)
    .then(function() {
      myCallback()
         .waitForVisible(HomePage.signInDropdown, 10000)
         .click(HomePage.signInDropdown);
    }
}

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