In the code below I want to call checkMainBox(cthis)
. I want to set it up so that this function will either return the number retrieved or false. But in checkMainBox()
I don't know how to return a value. number is returned undefined. I'm pretty sure I can't to do it this way because of asynchronous behavior but what is the next best way?
function checkMainBox(cthis){
var number;
cthis.waitForSelector("._XWk", function(){
cthis.capture("result.png");
cthis.then(function(){
var number = cthis.evaluate(function(){
return $("._XWk").txt();
})
// console.log("number", number);
})
})
return number
}
function getPhoneNumber(cthis){
console.log("NUMBER::", checkMainBox(cthis));
//checkMainBox(cthis) should return false or the number
}
casper.on("error", function(msg){
this.echo("error: " + msg, "Error");
})
casper.on("page.error", function(msg, trace){
this.echo("Page Error: " + msg, "error");
});
casper.on("remote.message", function(message){
this.echo("Remote: " + message);
});
casper.start("http://google.com/", function(){
this.waitForSelector("form[action='/search']");
});
casper.then(function(){
this.fill("form[action='/search']", {q : "ebay.com phone number"}, true);
})
casper.then(function(){
getPhoneNumber(this)
})
casper.run();
EDIT::
recent attempt with promise but if you have another way to do it feel free to share it:
function checkMainBox(cthis){
var number;
return new Promise(function(resolve, reject){
cthis.waitForSelector("._XWk", function(){
cthis.capture("result.png");
cthis.then(function(){
var number = cthis.evaluate(function(){
return $("._XWk").txt();
})
resolve(number)
})
});
})
}
function getPhoneNumber(cthis){
checkMainBox(cthis).then(function(result){
console.log("NUMBER::", checkMainBox(result));
})
.catch(function(err){
if(err) console.log(err);
})
}
ERROR : error: ReferenceError: Can't find variable: Promise
EDIT 2 :
function getPhoneNumber(cthis){
// var number;
cthis.waitForSelector("._XWk", function(){
cthis.capture("result.png");
cthis.then(function(){
var number = cthis.evaluate(function(){
return $("._XWk").html();
})
checkMainBox(number);
// console.log("number", number);
})
})
}
function checkMainBox (number){
// console.log("NUMBER::", number);
return number
}
...
casper.then(function(){
this.fill("form[action='/search']", {q : "ebay.com phone number"}, true);
})
casper.then(function(){
var number;
console.log(getPhoneNumber(this)) // should be the value
})
casper.run();