0

I'm trying to update rowNumber variable from within rows.each(), however when I console.log it afterwards, it's still set to null. What am I doing wrong? I've even tried defining var rowNumber 'higher', same result.

var licenceNumber = 233521673;

it('should open created Driver Licence', function() {
    var rowNumber = null;

    var rows = element.all(by.repeater('(rowRenderIndex, row) in rowContainer.renderedRows track by $index'));

    rows.each(function(element, index) {
        element.getText().then(function (text) {
            if (text.includes(licenceNumber)) {
                rowNumber = index;
                return true;
            }
        });
    });
    console.log('rowNumber = ', rowNumber);
});
5
  • 3
    it appears getText() returns a promise, and so the "then" callback will be async. Consequently it's entirely possible your console.log will run before that has executed and consequently the value has not yet been updated Commented Apr 25, 2018 at 14:45
  • Correct, console.log gets executed before getText() Commented Apr 25, 2018 at 14:51
  • @LazioTibijczyk is there anything else you need clarified, or do you understand the problem now? Commented Apr 25, 2018 at 14:53
  • @LazioTibijczyk ok glad that's confirmed. So if you want to see the value you can just move the console.log inside the "then" function Commented Apr 25, 2018 at 14:54
  • My idea was to get console.log to execute after rows.each(). I understand the problem now. I've added a new it() test and, it is executed in sequence anyway. Thanks for your help. Commented Apr 25, 2018 at 14:57

1 Answer 1

1

Use Promise.all to wait until all of the promises have resolved:

var licenceNumber = 233521673;

it('should open created Driver Licence', function() {
    var rowNumber = null;

    var rows = element.all(by.repeater('(rowRenderIndex, row) in rowContainer.renderedRows track by $index'));

    var promises = [];

    rows.each(function(element, index) {
        var promise = element.getText().then(function (text) {
            if (text.includes(licenceNumber)) {
                rowNumber = index;
            }
        });
        promises.push(promise);
    });

    return Promise.all(promises).then(function () {
        console.log('rowNumber = ', rowNumber);
    });
});

Note that the promise chained onto Promise.all is also returned to Mocha. This is important because it tells Mocha that this test is asynchronous, and will not be considered complete until that returned promise either resolves or rejects. Read more about this here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.