Nick Manning
Nick Manning

Reputation: 2989

Inner function doesn't know variable defined in outer scope. Why?

I'm trying to navigate through pages of an online dictionary. Here is my code:

var Nightmare = require('nightmare');
var nightmare = Nightmare({ show: true });

var links = [];
function goToLink(linkName){
    nightmare
        .goto(linkName)
        .evaluate( () => {
            var href = document.querySelector("span.next a").href;
            links.push(href)
            return href;
        })
        .then((href) => {
            goToLink(href);
        })
        .catch((error) => {
            console.error('Error:', error);
        });
}

goToLink("http://lexicon.quranic-research.net/data/01_a/000_!.html");

I'm getting Error: links is not defined. Links is clearly defined at var links = []; but the inner function doesn't know about it. What is going on here?

Upvotes: 1

Views: 68

Answers (1)

Filip Koblański
Filip Koblański

Reputation: 9988

The problem is that evaluate callback is called in a different context and doesn't see links. What you can try to do is to pass it like this:

(...)
.evaluate( links => {
    var href = document.querySelector("span.next a").href;
    links.push(href)
    return href;
}, links)
(...)

links are the parameter of the callback. You have to pass it as a second parameter in the evaluate function.

Upvotes: 1

Related Questions