0

I have a a test script in Node js which should ideally run sequentially. There are some functions which do not return anything but just perform certain operations like navigating to a menu or doing a key presses. Also, in my test I am making GET and POST request. Because of this sometimes if I have 10 steps and making a request is step 5, sometimes step 6 and 7 get executed before 5. I understand I should be using promises or callback. But I am unsure on how to use them in functions which do not return anything. Here is what my code looks like

browser.url(browser.options.baseUrl);
browser.waitForVisible(myLibraryPO.pageTitle, 15000, false);
let token = getTokenFromLocalStorage()
settingsPO.resetProgram(token); // POST call
browser.refresh();
guidePO.launchA();
guidePO.launchB();
guidePO.filter('NEWS');
guidePO.switchToC();
verifySettings(token,'NEWS'); // GET call
Kandarp Gandhi
  • 279
  • 2
  • 14
  • do some research on reduce ... for example https://stackoverflow.com/a/45022552/147175 – Scott Stensland Mar 30 '18 at 16:47
  • If you have a function that does some sort of asynchronous operation and you want to know when it's done, then it has to either return a promise or accept a callback as an argument or invent some other means of notifying completion. You have to fix those functions. You can't know when they're done or wait for them to be done before proceeding unless they do one of those. Functions that don't do anything asynchronous are done when they return so you don't have to mess with those. – jfriend00 Mar 30 '18 at 16:49
  • You need to show more code. All you've done here is shown us the function invocations... we don't have telepathy to automatically know what these functions are doing. Depending on your Node.js version, you can use the async/await syntax, or resort to using a promise chain. – dvsoukup Mar 30 '18 at 17:51

1 Answers1

1

You just call resolve() or reject() when you are done executing your function.

doSomething() {
  return new Promise((resolve, reject) => {
    //do some stuff...

    if(done) {
      resolve();
    }

    //call reject if something isn't right
    reject('something went wrong');
  });
}

Calling doSomething would look like this:

doSomething().then(() => {
  //you did something and returned an empty promise
});

or

await doSomething();
tehbeardedone
  • 2,833
  • 1
  • 15
  • 23
  • I am using browser.call() utility [http://webdriver.io/api/utility/call.html](webdriverio) which makes sure the async call gets implemented and then execution move forwards. It internally uses promises in a similar way. – Kandarp Gandhi Apr 03 '18 at 20:21