What is the equivalent of this Coffescript code in Javascript? [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
phantom = require 'phantom'
phantom.create (ph) ->
ph.createPage (page) ->
page.open "http://www.google.com", (status) ->
console.log "opened google? ", status
page.evaluate (-> document.title), (result) ->
console.log 'Page title is ' + result
ph.exit()
I tried using this website but it doesn't seem to be very accurate. It has returns everywhere. http://js2coffee.org/#coffee2js

Update: After a second look, it does seem that some of these returns are spurious/redundant. That is because Coffeescript just always returns the result of the last statement in the function (so that you can save the return keyword), even in cases where you would not have returned anything in Javascript (the compiler cannot know your intention here). That may be unnecessary, but there is also no harm in it, if no one was using the return value anyway. If it is somehow important to return "nothing", you'd can explicitly do that, too.
You can just compile it, to see what it results in:
var phantom;
phantom = require('phantom');
phantom.create(function(ph) {
return ph.createPage(function(page) {
return page.open("http://www.google.com", function(status) {
console.log("opened google? ", status);
return page.evaluate((function() {
return document.title;
}), function(result) {
console.log('Page title is ' + result);
return ph.exit();
});
});
});
});
It has returns everywhere.
Well, every function you define there has one return.
One of the prime motivators for Coffeescript is to be able to write all those callback functions with less boilerplate.
Either way, the compiler is "accurate".

var phantom = require('phantom');
phantom.create(function(ph)) {
ph.createPage(function(page) {
page.open("http://www.google.com", function(status) {
console.log("opened google? ", status);
page.evaluate(function() { return document.title; }, function() {
console.log('Page title is ' + result);
ph.exit()
}
});
});
});

Related

second time function not calling [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 months ago.
Improve this question
when i call Javascript function first time it work properly but second time it get error like
Uncaught TypeError: profile is not a function at HTMLImageElement.onclick
why it happening?
try to write function in head section of html as well as js file but didn't working!
function profile_detail(){
xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost/CI-social-media/index.php/profile_detail", false);
xhr.onload = () => {
if (xhr.status == 200) {
if (xhr.response) {
profile = JSON.parse(xhr.responseText);
// console.log(xhr.response);
console.log(xhr.response);
console.log(profile);
// document.getElementById("profile_photo").innerHTML =xhr.response;
document.getElementById("profile_photo").src = profile[0]["profile"];
document.getElementById("profile_name").innerHTML = profile[0]["display_name"];
document.getElementById("username").innerHTML = "#"+ profile[0]["user_name"];
}
else {
alert("something want wrong try agin later")
}
}
else {
alert("Something Want Wrong Try agin");
}
}
xhr.send();
}
function profile(){
document.getElementById("request").style.display="none";
document.getElementById("friend_list").style.display="none";
document.getElementById("msg_section").style.display="none";
document.getElementById("friend_search").style.display="none";
document.getElementById("home_mains").style.display="none";
document.getElementById("search_friend_main").style.display="none";
document.getElementById("search1").style.display="none";
document.getElementById("rrprofile-card").style.display="flex";
profile_detail();
}
There are many reasons for the that
1. In first time call the function it's remove the itself ( function )
For example you use innerHtml = "" in head section
sometimes happening
.
2. You use a same name for variable and function
Mostly having this error

How to properly close phantomjs webpage after use?

I'm trying to read some data from 200+ web pages with PhantomJS and typescript/rxjs
What I came up so far is this
Observable.fromPromise(phantom.createPage()).flatMap(jobPage => {
return Observable.fromPromise(jobPage.open(url)).flatMap(status => {
if (status !== "success") {
console.error("Couldn't load job page for url " + url + " Status: " + status);
jobPage.close();
return Observable.of(undefined)
} else {
return Observable.fromPromise(jobPage.evaluate(function () {
//do some content reading, return data
return data;
}));
}
});
})
And it works, but with every page it gets slower and slower, and finally ends with Memory Exhausted message from Phantom. I guess it's because I do not close the web pages I'm creating, but I dont have any idea how to do it such case (flatMap creates a new one, I need it for extraction later, and Observable.fromPromise() does not allow me to close the page after I'm done.
Any help is appreciated
Ok, figured it out, just need to use
Observable.fromPromise(phantom.createPage()).flatMap(jobPage => {
//stuff as before
}).finally(function(){
jobPage.close();
})

Do multiple promises on an array of elements [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have a list of objectIds and I want to go to different collections and do operations base on each Id. I would prefer doing the operation one after the other (sequentially)
var removeOperation = function(objectified){
return Comps.findOne({reviews : objectified}).populate([{ path: "reviews", match : {_id : objectified}}])
}
var firstCheckIfAnonHasTheIdInReviewsArrayIfThereDeleteIt = function(objectified){
var query = {reviews : objectified};
var update = {$pull : {reviews : objectified}};
var option = {new :true};
return Anon.findOneAndUpdate(query, update, option );
};
var thenCheckIfUserHasTheIdInReviewsArrayIfThereDeleteIt = function(objectified){
var query = {reviews : objectified};
var update = {$pull : {reviews : objectified}};
var option = {new :true};
return User.findOneAndUpdate(query, update, option );
}
I was going down this path:
Promise.mapSeries(arrOfObjectIds, function(e){
return removeOperation(e);
})
.then(function(results){
console.log(results);
var map = results.map(function(e){
// return e.reviews[0]
return e
})
console.log("map : ", map)
return Promise.resolve(map);
})
.then(function(compDocs){
console.log("compDocs: ",compDocs)
Promise.mapSeries(compDocs, function(compDoc){
return updateCompAndRemoveReviewFromArray(compDoc) // I know it's not show. It's another promise I use
})
}).then(function(returned){
return Reviews.remove({_id : {$in : arrOfObjectIds }})
})
.then(function(){
I wanted to do firstCheckIfAnonHasTheIdInReviewsArrayIfThereDeleteIt on the array of object Ids to delete the review from the array. Also if we succesfully removed the array here we should not have to go to the next user
promise which deletes a users review since if we deleted in Anon it won't be in User. since there is only one review ID possible per review.
})
.then(function(){
//if there was no review pulled from the Anon reviews Array. that means it's in the users review and we should do this promise
thenCheckIfUserHasTheIdInReviewsArrayIfThereDeleteIt()
})
So maybe you can show me how to use mapSeries on an array of elements so that it just doesn't d one promise but does multiple promises.
can we doe something like:
Promise.mapSeries(arrOfObjectIds, function(e){
return removeOperation(e);
return firstCheckIfAnonHasTheIdInReviewsArrayIfThereDeleteIt(e)// extra credit: check if this was successful (review was pulled). If it wasn't got to next one.
return thenCheckIfUserHasTheIdInReviewsArrayIfThereDeleteIt(e)
})
Restating the problem in simplified terms :
You have an array of IDs and for each ID in turn you want to call three promise-returning functions, A, B and C as follows :
A(id) (unconditionally)
then B(id) (unconditionally)
then C(id) (conditionally, depending on the outcome of B(id))
Can we do something like:
Promise.mapSeries(arrOfObjectIds, function(e){
return removeOperation(e);
return firstCheckIfAnonHasTheIdInReviewsArrayIfThereDeleteIt(e)// extra credit: check if this was successful (review was pulled). If it wasn't got to next one.
return thenCheckIfUserHasTheIdInReviewsArrayIfThereDeleteIt(e)
})
Yes, though not very like the suggested code.
First, you have a design choice concerning the way in which B reports its outcome. The question hints at B's outcome being a case of "success" vs "failure", but that's not the only way to model it.
Option 1: Test data delivered down the promise chain's success path
Write B such that its returned promise will fulfill both on success (Anon review was deleted) or on the expected failure (Anon review was not deleted), and report the outcome by means of a parameter.
var B = function(objectified) {
var query = {reviews: objectified};
var update = {$pull: {reviews: objectified}};
var option = {new :true};
return Anon.findOneAndUpdate(query, update, option).exec();
};
Then you would write :
Promise.mapSeries(arrOfObjectIds, function(id) {
return A(id).then(function() {
return B(id);
}).then(function(item) { // item will be `null` if B(id) found nothing.
return item || C(id);
}).catch(function(error) {
// If anything went wrong, catch the error and log it.
console.log(error);
// By not re-throwing the error, the mapseries() is allowed to continue.
});
});
Option 2: Test error delivered down the promise chain's failure path
Write B such that its returned promise will fulfill on success, or reject on expected failure.
var B = function(objectified) {
var query = {reviews: objectified};
var update = {$pull: {reviews: objectified}};
var option = {new :true};
return Anon.findOneAndUpdate(query, update, option).exec().then(function(item) {
return item || Promise.reject(new Error('not found'));
});
};
Then you would write :
Promise.mapSeries(arrOfObjectIds, function(id) {
return A(id).then(function() {
return B(id).catch(function(error) {
// Here, you have to discriminate between the "expected error" and any unexpected errors.
if(error.message === 'not found') {
return C(id);
} else {
throw error; // unexpected error - rethrow it
}
});
}).catch(function(error) {
// If anything went wrong, catch the error and log it.
console.log(error);
// By not re-throwing the error, the overall mapseries() is allowed to continue.
});
});
In both options :
to return a genuine Promise, use .exec() in A, B and C. (As I understand Mongoose, without exec() you get something which has a .then() method, but which is not a full-blown Promise).
if you want the overall sequence to stop on first error, then rethrow the error after logging it, or completely omit the final catch().
further unconditional stages can be added very simply, before or after the conditional stage.
For me, Option 2 is more logical, though I would probably choose Option 1 for its greater simplicity and efficiency.
You can use Array.reduce() to execute your promises in series:
arrOfObjectIds.reduce(function(promise, objectId) {
return promise.then(function(result) {
return removeOperation(objectId)
.then(firstCheckIfAnonHasTheIdInReviewsArrayIfThereDeleteIt)
.then(thenCheckIfUserHasTheIdInReviewsArrayIfThereDeleteIt);
});
}, Promise.resolve());
This will perform the chain of removeOperation -> firstCheck.. -> thenCheck one item in the array at a time, then move to the next item.
can we doe something like: yes, like that, except the first return exits the function
so, you could possibly do something like
Promise.mapSeries(arrOfObjectIds, function(e){
return removeOperation(e)
.then(function() {
return firstCheckIfAnonHasTheIdInReviewsArrayIfThereDeleteIt(e);
}).then(function() {
return thenCheckIfUserHasTheIdInReviewsArrayIfThereDeleteIt(e);
})
})

Calling asynchronous function in callback

I'm having some trouble understanding asynchronous functions. I've read the chapter in Mixu's Node Book but I still can't wrap my head around it.
Basically I want to request a ressource (using the node package cheerio), parse it for valid URLs and add every match to my redis set setname.
The problem is that in the end it's only adding the first match to the redis set.
function parse(url, setname)
{
request(url, function (error, response, body)
{
if (!error && response.statusCode == 200)
{
$ = cheerio.load(body)
// For every 'a' tag in the body
$('a').each(function()
{
// Add blog URL to redis if not already there.
var blog = $(this).attr('href')
console.log("test [all]: " + blog);
// filter valid URLs
var regex = /http:\/\/[^www]*.example.com\//
var result = blog.match(regex);
if(result != null)
{
console.log("test [filtered]: " + result[0]);
redis.sismember(setname, result[0], function(err, reply)
{
if(!reply)
{
redis.sadd(setname, result[0])
console.log("Added " + result[0])
}
redis.quit()
})
}
})
}
})
}
I'd be very grateful for pointers on how I'd have to restructure this so the redis.sadd method is working with the correct result.
The output of the current implementation looks like:
test [all]: http://test1.example.com/
test [filtered]: http://test1.example.com/
...
Added http://test2.example.com/
So it's adding the test1.example.com but not printing the "added" line, and it's not adding the test2.example.com but it's printing the "added" line for it.
Thank you!
The first issue is caused by redis.sismember() being asynchronous: when its callback is called, you have already overwritten the result variable so it will point to the last value it had, and not the value at the moment at which you called redis.sismember().
One way to solve that is to create a new scoped variable by wrapping the asynchronous function in a closure:
(function(result) {
redis.sismember(setname, result[0], function(err, reply) {
...
});
})(result);
Another option is to create a partial function that's used as callback:
redis.sismember(setname, result[0], function(result, err, reply) {
...
}.bind(this, result));
The second issue is, I think, caused by redis.quit() being called, which closes the Redis connection after the first sadd(). You're not checking err, but if you do it might tell you more.

When to consolidate methods - migrate [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
Below are my 7 call back methods for ajax. They are all similar in structure so that if I wanted I could abstract out the code into generic methods, call these generic methods, and modify them with input parameters/arguments.
However, I'm trying to determine the point at which consolidation is worth the effort. Furthermore, what is considered best practice?
Shold I consolidate these methods?
/*
consolidate these ajax call back functions
*/
function ajax_signup(a,b)
{
c=check_aml(a.slice(0,6));
if(c===0)
{
document.f1_1.submit(); // on pass submit the file upload form
}
else if(c===1)
{
document.getElementById(b).innerHTML=a; // on fail report to user
}
else if(c===2)
{
a=a.substr(6);
alert('php error: ' + a); // on php error
}
}
function ajax_signin(a,b)
{
c=check_aml(a.slice(0,6));
if(c===0)
{
m6(); // on pass reload the page
}
else if(c===1)
{
document.getElementById(b).innerHTML=''; // on fail report to the user
document.getElementById(b).innerHTML=a;
}
else if(c===2)
{
a=a.substr(6);
alert('php error: ' + a); // on php error
}
}
/*
Takes in sturctured data and convert to xhtml - remove the conversion into another method
*/
function ajax_tweet(a,b)
{
var c,d,e,f='';
var g=a.slice(0,6); // prepare status
var h=check_aml(g); // check for status
if(h===0)
{
c=a.split(/\|\|/);
for(e=0;e<c.length;e++)
{
d=c[e].split(/\|/);
f=f+'<div class="Bb2b"><img class="a" src="pictures/' + d[0] + '.jpg" alt=""/><a class="a" href="javascript:void(0)\">' + d[1] + ' posted ' + view_date(d[2],d[3]) + '</a><br/><p class="c">' + d[4] + '</p></div>';
}
m2(b,f);
}
else if (h===1) // on tweet fail - add in graceful fail <xx_f>
{;}
else if (h===2)
{
a=a.substr(6);
alert('php error: ' + a); // on php error
}
}
/*
Ajax call-back methods - do nothing but report a PHP error if it ocurred. On a success of and add or delete there is no message to the user. Need to add in a graceful fail, ie. <xx_f>.
*/
function ajax_bookmark(a,b)
{
c=a.slice(0,6);
d=check_aml(c);
if(d===0)
{;}
else if (d===1)
{;}
else if (d===2)
{
a=a.substr(6);
alert('php error: ' + a);
}
}
function ajax_bookmark_add(a,b)
{
ajax_bookmark(a,b);
}
function ajax_bookmark_delete(a,b)
{
ajax_bookmark(a,b);
}
/*
Place holder for method parameter
*/
function ajax_null()
{
}
Look into groupping using the module pattern or regular object instatination.

Categories