简体   繁体   中英

JavaScript Protractor While loop never ending

I'm writing JavaScript tests with Protractor

Recently I got an error:

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory

But it surely isn't a memory error, I found out something's wrong with that function:

ProfilePage.prototype.removeProgrammingLanguages = function () {
    i=0;
    while (i < 3) {
        browser.findElement(By.css("//div/span")).then(null, function (err) {
            if (err.name == "NoSuchElementError") {
                i=11;
            }
        this.programmingLanguagesRemoveButton.click();
        i++;
        });
    }
};

I want protractor to click a button until find element returns a NoSuchElementError (remove all elements from a list).

What's wrong?

I finally managed to do this

ProfilePage.prototype.removeProgrammingLanguages = function removeProgrLanguages() {
    browser.findElement(By.xpath("//div/span")).then(function (err) {
        element(By.css("div.lang-cloud.remove > span")).click().then(removeProgrLanguages);
    }, function (err) {
        if (err) {
            console.log(err.name);
        } else {
                promise.rejected();
        }
    })
};

This loop fires promises as fast as your cpu can create them. You are not making the loop wait for the promise to resolve. So it creates one then moves to the next line of code. Which is a new loop to create one. It will have created thousands of promises before the first one resolves.

You can use Promise.resolve() to wait for a promise to be resolved.

however you could also solve this by recursively chaining promises like so:

ProfilePage.prototype.removeProgrammingLanguages = function removeProgrammingLanguages() {
    return browser.findElement(By.xpath("//div/span")).then(function() {
        this.programmingLanguagesRemoveBttn = element(By.css("div.lang-cloud.remove > span"));
        return this.programmingLanguagesRemoveBttn.click().then(removeProgrammingLanguages)
    })
};

This function will stop when a promise is rejected. You will have to change the 'this' reference, because they go funny inside promises.

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