gosferano
gosferano

Reputation: 35

JS undefined promise

I'm new to node.js and protractor end-to-end testing and might be I don't know something really simple, but I just couldn't find an answer.

I have a for loop in which I want to get data from a function which returns a promise. Code chunk looks like this:

for (var i=2; i<Math.ceil(searchTotal/pageSize)+1; i++) {
    checkNext(i, pageSize, searchTotal).then( function(pageData){
        console.log(pageData + ' PENDING ');
        if (!pageData.isCorrect) {
            console.log(pageData + ' FAILED');
            expect(pageData.searchText).toEqual(pageData.formedText);
        }
        else if (i == Math.ceil(searchTotal/pageSize)) {
            console.log(pageData + ' SUCCEEDED');
            expect(pageData.searchText).toEqual(pageData.oldText);
        }
    })
}

Thing is, pageData is undefined all the time.

Would be glad if somebody could point out my mistake.

Upvotes: 0

Views: 87

Answers (2)

Brine
Brine

Reputation: 3731

One of the issues you may be facing is async looping. Async looping is hard. Luckily, there are many, many answers here on Stack. Because it's async, node will burn through your loop and then pass only the last value.

With the code provided, I can't offer a specific example, but one general example (see other answers for more ways) is to use a function and pass in your index. This can even be an anonymous function that immediately fires. Eg:

for(var i = 0; i < somethings.length; i++) {
    (function(i) {
        expect(someOtherThing.get(i).isDisplayed()).toBe(true);
    })(i);
}

Hope that helps

Upvotes: 0

martin770
martin770

Reputation: 1288

Make sure you have a return in checkNext. If you don't explicitly return something, a promise will return undefined.

Upvotes: 1

Related Questions