Friday 21 July 2017

NodeJS and PhantomJS consecutive promises. Last one not being fired

I am using PhantomJS to login a website using node.js. After that I want to make an HTTP request to obtain a json with data. My code is as follows:phantom.create() .then(function (ph) { this.ph = ph; return ph.createPage(); }) .then(function (page) { this.page = page; return page.open('https://example.com'); }) .then(function (status) { if ( status === "success" ) { return this.page.evaluate(function() { document.querySelector("input[name='j_username']").value = 'example@example.net'; document.querySelector("input[name='j_password']").value = 'example'; console.log('Submitting logging...'); document.querySelector("input[name='submit']").click(); }); } else { return null; } }) .then(function() { console.log("Logged in!"); return new Promise(function(resolve, reject) { this.page.property('onResourceRequested', function(requestData, networkRequest) { //This event is fired 40 times, only one is interesting to me the one that has the text maps.json in it if (requestData.url.indexOf('maps.json') !== -1) { //This if clause is entered only once like 10 seconds after "Logged in" console log and after being fired like 35 times for the other requests resolve({headers: requestData.headers, url: requestData.url}); } }); }); }); .then(function (data) { //This then block is never fired if (data) { console.log(data); request.get({ uri: data.url, headers: data.headers }, function(err, res, body){ if (!err) { callback(null, res.headers); } else { console.log("Error getting data from URL: "+ err); callback(true, null); } }); } }); There must be something wrong with the second last returned promise because the last then() is never fired although I can see that if (requestData.url.indexOf('maps.json') !== -1) is accesed once if I add a console.log inside...I am stuck in this for two days now..can someone help me?

Submitted July 21, 2017 at 09:27AM by jaitor

No comments:

Post a Comment