Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Sedro
Dec 31, 2008

o.m. 94 posted:

It is subtleties like this so easily encountered which makes me laugh whenever someone recommends JavaScript as a beginner's language
You'll have the same problem in every language. You close over a mutable value, what do you expect?

The canonical JS example is when you declare the variable inside the loop, but it gets hoisted out and you see the same behavior. It's weird depending on what language you come from but not hard to understand.

Adbot
ADBOT LOVES YOU

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

o.m. 94 posted:

It is subtleties like this so easily encountered which makes me laugh whenever someone recommends JavaScript as a beginner's language

The only reason JavaScript could be considered that is because every computer has several JavaScript interpreters already installed.

qntm
Jun 17, 2009
The precise same behaviour is present in Python as well, and I expect every language with in-line function declarations and implicit capture by reference.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

Wheany posted:

The only reason JavaScript could be considered that is because every computer has several JavaScript interpreters already installed.

(A pretty good reason.)

HappyHippo
Nov 19, 2003
Do you have an Air Miles Card?
Closing over the loop variable is something everyone gets burned by once. It can happen in most any language with closures.

Ironically, I would say it's javascript's "beginner friendly" features that make it a not so great beginner language. Things like weak typing, automatic globals, semicolon insertion, and just the general attitude of chugging along after errors all make it difficult for a beginner to figure out what's going on, and encourage voodoo programming.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Opulent Ceremony posted:

I'd post the link to the canonical "JavaScript closure example" since the problem code is almost exactly what was posted but I can't find it.

Just check http://stackoverflow.com/questions/tagged/javascript - there's probably one or two on there at all times.

enthe0s
Oct 24, 2010

In another few hours, the sun will rise!

Wheany posted:

JavaScript code:
var getHandler = function (num) {
	return function () {
		alert(num);
	};
};

$(function(){
    var i;
    for (i=0; i<2; i++){
        $('#div'+i).click(getHandler(i));
    }
});
JS has function scope. Your alert(i) refers to the i in the for loop whose value is 2 after the loop has run.

edit: Doing anything by concatenating strings is usually a horror.

Does this accomplish the same thing or am I missing something?
JavaScript code:
var getHandler = function (num) {
	alert(num);
};

Sedro
Dec 31, 2008

enthe0s posted:

Does this accomplish the same thing or am I missing something?
JavaScript code:
var getHandler = function (num) {
	alert(num);
};

Then getHandler(i) would call the function, which would display the alert and evaluate to undefined (default return value). So you end up calling $('#div'+i).click(undefined);

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

enthe0s posted:

Does this accomplish the same thing or am I missing something?
JavaScript code:
var getHandler = function (num) {
	alert(num);
};

Your code runs the function immediately, my code returns a function to be called later.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
What are people's thoughts on the current climate of altJS languages?

I'm about to take a dive into learning Dart because there's a specific project that I'd like to contribute to. Will my time spent learning be a sunk cost after this particular piece of work is done? Is it conceivable that having demonstrable skill with Dart will help my employability? Searching 'Dart' on stackoverflow careers turns up a bunch of companies who have dart boards...

5TonsOfFlax
Aug 31, 2001

Newf posted:

What are people's thoughts on the current climate of altJS languages?

I'm about to take a dive into learning Dart because there's a specific project that I'd like to contribute to. Will my time spent learning be a sunk cost after this particular piece of work is done? Is it conceivable that having demonstrable skill with Dart will help my employability? Searching 'Dart' on stackoverflow careers turns up a bunch of companies who have dart boards...

Yeah, Dart is impossible to search for because you always get trucking jobs, Dallas public transit, and dart boards. But the language itself is great if you prefer a more classic object oriented and strongly typed approach.

Gounads
Mar 13, 2013

Where am I?
How did I get here?

Newf posted:

What are people's thoughts on the current climate of altJS languages?

I'm about to take a dive into learning Dart because there's a specific project that I'd like to contribute to. Will my time spent learning be a sunk cost after this particular piece of work is done? Is it conceivable that having demonstrable skill with Dart will help my employability? Searching 'Dart' on stackoverflow careers turns up a bunch of companies who have dart boards...

I built an app in Angular/Dart, it was awesome.

But... the angular/dart team is off working on Angular 2 using AtScript with some hand-waving saying they will cross-compile to dart. So there is much fear in that community. My guess is companies that aren't using it already will avoid it.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Newf posted:

What are people's thoughts on the current climate of altJS languages?

I'm about to take a dive into learning Dart because there's a specific project that I'd like to contribute to. Will my time spent learning be a sunk cost after this particular piece of work is done? Is it conceivable that having demonstrable skill with Dart will help my employability? Searching 'Dart' on stackoverflow careers turns up a bunch of companies who have dart boards...

My hunch is that no altjs language is as useful as being real good at just pure JavaScript. Anything you know in addition is is just nice to know, unless you're applying for a job in a project that uses one.

The Insect Court
Nov 22, 2012

by FactsAreUseless

Newf posted:

What are people's thoughts on the current climate of altJS languages?

I'm about to take a dive into learning Dart because there's a specific project that I'd like to contribute to. Will my time spent learning be a sunk cost after this particular piece of work is done? Is it conceivable that having demonstrable skill with Dart will help my employability? Searching 'Dart' on stackoverflow careers turns up a bunch of companies who have dart boards...

The only real advantage of altJs language is that you get a language with the sort of features that any respectable modern language should have. Atscript/Typescript seem useful in this regard in that they add some basic modularity/encapsulation/typing while still remaining syntactically and semantically similar to Javascript. It's not so much that it helps on a resume(probably a lot less than knowing whatever big relevant JS frameworks/libraries/platforms there are for the job) but that you can produce code that's more maintainable and reliable.

The other alternative is a big boy language that can be compiled to Javascript like Clojure/Scala/Kotlin. But those all make Javascript interop a lot more difficult, and with the sorta exception of Clojurescript none have sizeable communities or a reasonably sure future.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
Thanks for the feedback folks. I'll keep concentrating on improving my js knowledge, and probably just pick up enough Dart to scrape by on my immediate needs. As it happens, I cracked open the two Dart packages that I aim to mush together last night, and didn't have any trouble getting started.


This bit from the dart tutorial is shockingly on-the-nose with my previous posted problem:

code:
// Closures inside of Dart’s for loops capture the value of the index,
// avoiding a common pitfall found in JavaScript. For example, consider:

var callbacks = [];
for (var i = 0; i < 2; i++) {
  callbacks.add(() => print(i));
}
callbacks.forEach((c) => c());

// The output is 0 and then 1, as expected. In contrast, the example
// would print 2 and then 2 in JavaScript.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

So is ES6: http://es6rocks.com/2014/08/what-you-need-to-know-about-block-scope-let/

leftist heap
Feb 28, 2013

Fun Shoe
Good god that guy's Ubuntu dock is horrifying!

All the altJS languages remind me of all the attempts at creating a "better Java" on the JVM. The languages were always immature, poorly supported, came with their own host of problems, etc. Adoption never really goes anywhere and in the meantime the native language keeps getting better and better and diminishes the need for the supposed "better" language.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

rrrrrrrrrrrt posted:

Good god that guy's Ubuntu dock is horrifying!

All the altJS languages remind me of all the attempts at creating a "better Java" on the JVM. The languages were always immature, poorly supported, came with their own host of problems, etc. Adoption never really goes anywhere and in the meantime the native language keeps getting better and better and diminishes the need for the supposed "better" language.

Yeah, try writing some ES6 with the Traceur compiler, its pretty nice.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Maluco Marinero posted:

Yeah, try writing some ES6 with the Traceur compiler, its pretty nice.

I was just experimenting with integrating this into my React workflow today and you're right. It's pretty sweet.

vanmartin
Feb 2, 2005
WWBD?
So... any opinions on Node.js being forked?

quote:

A group headed by some of Node’s most important contributors has "forked" the project, creating a new version it's calling io.js. It’s a version of Node “where contributions, releases, and contributorship are under an open governance model,” its Readme file states.

More here: http://readwrite.com/2014/12/04/node-js-fork-io-js

Best outcome, in my opinion, would be for Joyent to place Node.js in a foundation which would hopefully prevent two major but ultimately divergent branches being created over time.

obstipator
Nov 8, 2009

by FactsAreUseless

vanmartin posted:

So... any opinions on Node.js being forked?


More here: http://readwrite.com/2014/12/04/node-js-fork-io-js

Best outcome, in my opinion, would be for Joyent to place Node.js in a foundation which would hopefully prevent two major but ultimately divergent branches being created over time.

Oh god, this is really stupid. It sounds like that power struggle between the companies the top contributors work for is still going on. Each of them want to be the "owners" of node so they can become the definite source for support and therefore make the most money. And it sounds like the current tactic to meet that end is to split node and gently caress up the community in the process. I haven't paid much attention to the current feuds going on, but this is likely all about money and talking poo poo about the other contributors.

This is probably a lot like the time the CEO of one company publicly called a rival top contributor an rear end in a top hat on the company blog because the guy wasn't a native english speaker and didn't understand that "he" vs "he or she" was a big deal to some people. They just want more power and will do whatever poo poo they can to get that power.

PleasureKevin
Jan 2, 2011

hello i'm new to the 'script

how do i make a blank property that will hold a page element? eg.

pre:
myFunElement = getElementById('weedBong');

function Bong() {
    this.bongToLoad = {}; //this part i don't know

    load = function () {
        this.bongToLoad.getContext('4d');
        this.bong.stroke();
    }
}

function bongify() {
    var theBong = new Bong;
    theBong.bongToLoad = myFunElement;
    myBong.load();
}

wow, i'm hilarious

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

PleasureKevin posted:

hello i'm new to the 'script

how do i make a blank property that will hold a page element? eg.

pre:
myFunElement = getElementById('weedBong');

function Bong() {
    this.bongToLoad = {}; //this part i don't know

    load = function () {
        this.bongToLoad.getContext('4d');
        this.bong.stroke();
    }
}

function bongify() {
    var theBong = new Bong;
    theBong.bongToLoad = myFunElement;
    myBong.load();
}

wow, i'm hilarious


JavaScript code:
myFunElement = getElementById('weedBong');

var theBong = {
	bongToLoad: myFunElement

    load: function () {
        this.bongToLoad.getContext('4d');
        this.bong.stroke();
    }
};

theBong.load();
edit: If you just want to have an empty property in your object, you can assign null to the property, or just leave them unassigned:

JavaScript code:
var aButt = {
	leftCheek: null,
	rightCheek: null
};
var anotherButt = {}

//both of these work
aButt.leftCheek = {
	fullness: 7
}
anotherButt.leftCheek = {
	fullness: 5
}

Wheany fucked around with this message at 17:11 on Dec 5, 2014

PleasureKevin
Jan 2, 2011

obstipator posted:

Oh god, this is really stupid. It sounds like that power struggle between the companies the top contributors work for is still going on. Each of them want to be the "owners" of node so they can become the definite source for support and therefore make the most money. And it sounds like the current tactic to meet that end is to split node and gently caress up the community in the process. I haven't paid much attention to the current feuds going on, but this is likely all about money and talking poo poo about the other contributors.

This is probably a lot like the time the CEO of one company publicly called a rival top contributor an rear end in a top hat on the company blog because the guy wasn't a native english speaker and didn't understand that "he" vs "he or she" was a big deal to some people. They just want more power and will do whatever poo poo they can to get that power.

Open governance has no "owners" or leaders. Also, to honour the amazing person who pushed the fork button we will release the first version of IO.js on Fedor's birthday all hail the new king!

Wheany posted:

JavaScript code:
myFunElement = getElementById('weedBong');

var theBong = {
	bongToLoad: myFunElement

    load: function () {
        this.bongToLoad.getContext('4d');
        this.bong.stroke();
    }
};

theBong.load();


But what about if I wanna load another bong element with that same object??

EDIT: OK thanks VV

PleasureKevin fucked around with this message at 17:13 on Dec 5, 2014

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

PleasureKevin posted:

But what about if I wanna load another bong element with that same object??

theBong.bongToload = anotherElement

obstipator
Nov 8, 2009

by FactsAreUseless

PleasureKevin posted:

wow, i'm hilarious

This post brought me a lot of pleasure, Kevin.

Hed
Mar 31, 2004

Fun Shoe
It's late and I'm trying to data unit testing of my Angular coverage--I'm following like an outdated book and some online guides and can't figure out what's going on here. This works:

JavaScript code:
//'use strict';

// ** snip **

describe('timekeeper.filters module', function() {
  beforeEach(function () {
    var app = module('timekeeper.filters');
  });
  beforeEach(inject(function($filter) {
    console.log(Object.keys( app ));
    console.log($filter('joinBy'));
    filter = $filter;
  }));
  describe('sumOfValue Unit Tests', function() {  
    it('dummy test 2', function() {
        expect(true).toBe(true);
    });
    it('filter exists', function() {
        expect(filter('sumOfValue')).not.toBeNull();
    });
    it('dummy test 3', function() {
      expect(true).toBe(true);
        //expect(filter('sumOfValue')(/* input data */)).toEqual(/* sorted data */);
    });
  });

});
The above is kind of how my book wants me to do testing. It works and produces a passing result. But the Angular guide (and common sense) says that I should leave 'use strict' on. However I can't just leave that filter assignment out there so I end up with:

JavaScript code:
'use strict';

describe('timekeeper.filters module', function() {
  beforeEach(function () {
    var app = module('timekeeper.filters');
  });
  beforeEach(inject(function($filter) {
    console.log(Object.keys( app ));
    console.log($filter('joinBy'));
    var filter = $filter;
  }));
  describe('sumOfValue Unit Tests', function() {  
    it('dummy test 2', function() {
        expect(true).toBe(true);
    });
    it('filter exists', function() {
        expect(filter('sumOfValue')).not.toBeNull();
    });
  });

});

which produces a "ReferenceError: Can't find variable: filter".
So my questions are--how should I be doing my unit tests since I want them to be as generic and decoupled as possible (i.e. only require my filters.js module, not my entire freaking app), and how should I be injecting dependencies into each bit of testing? Why does setting the filter as a variable in scope before each test raise the ReferenceError?

leftist heap
Feb 28, 2013

Fun Shoe
Because filter is only in scope inside your beforeEach. Declare the variable outside the beforeEach.

Hed
Mar 31, 2004

Fun Shoe
:doh: I got so locked in to treating the beforeEach as black magic I missed the obvious. Thanks!

Smerdyakov
Jul 8, 2008

I'm trying to make a very simple binary search tree so I can write/play with various functions that add onto it. What I want to do (I think) is give var mrbstree the property root with a value of 8 and then give the root property the properties left and right with values of 7 and 9, respectively.

This doesn't work
var mrbstree = {};
mrbstree.root = 8;
mrbstree.root.left = 7;
mrbstree.root.right = 9;

Edit: so the problem is that I was trying to assign properties to primitives, because I'm dumb. Is there any way other than this?

mrbstree.root = {value: 8};
mrbstree.root.left = {value: 7};
mrbstree.root.right = {value: 9};

I haven't seen any references to having a BST as an array of arrays, but would that be possible/not cause problems down the line?

Smerdyakov fucked around with this message at 20:25 on Dec 10, 2014

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
Your conception of a tree node is a little wonky - pairing this with low confidence in your JS syntax is going to make things hairy for you. A (binary) tree node has a value and left and right references to other tree nodes.

Have a look at this fiddle to get back on track: http://jsfiddle.net/fgy67832/.

Smerdyakov
Jul 8, 2008

Newf posted:

Your conception of a tree node is a little wonky - pairing this with low confidence in your JS syntax is going to make things hairy for you. A (binary) tree node has a value and left and right references to other tree nodes.

Have a look at this fiddle to get back on track: http://jsfiddle.net/fgy67832/.

Oh. Oh! That helps a lot and puts the other instructions I've got into the right context, thanks!

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic
I'm just starting to dive a little more deeply into objects, and have been fascinated with replacing switch statements with object literals

(http://toddmotto.com/deprecating-the-switch-statement-for-object-literals/)

Most of it I understand, but there's a piece of code that is throwing me

code:
function getDrink (type) {
  return 'The drink I chose was ' + {
    'coke': 'Coke',
    'pepsi': 'Pepsi',
    'lemonade': 'Lemonade'
  }[type];
}

getDrink('coke');
I don't fully understand the [type] after the return statement in the above. It's bracket notation, but I'm still not fully sure how the key is being queried.

If I'm calling for an object property, I'd say something like getDrink['coke'] which would give me the value 'Coke'. Is the above code basically being interpreted by JavaScript as my saying getDrink['coke']?

The return statement before the bracket notation is what is throwing me here.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Raskolnikov2089 posted:

I'm just starting to dive a little more deeply into objects, and have been fascinated with replacing switch statements with object literals

(http://toddmotto.com/deprecating-the-switch-statement-for-object-literals/)

Most of it I understand, but there's a piece of code that is throwing me

code:
function getDrink (type) {
  return 'The drink I chose was ' + {
    'coke': 'Coke',
    'pepsi': 'Pepsi',
    'lemonade': 'Lemonade'
  }[type];
}

getDrink('coke');
I don't fully understand the [type] after the return statement in the above. It's bracket notation, but I'm still not fully sure how the key is being queried.

If I'm calling for an object property, I'd say something like getDrink['coke'] which would give me the value 'Coke'. Is the above code basically being interpreted by JavaScript as my saying getDrink['coke']?

The return statement before the bracket notation is what is throwing me here.

Objects can have their keys queried by bracket notation:

JavaScript code:
var a = {"boo": "Yah"};
a.boo === a['boo']; // true, as both are "Yah"
The function uses this to do the lookup, and saves a couple steps by inlining the object creation and lookup and returning it right away. It is functionally equivalent to this:

JavaScript code:
function getDrink(type) {
    var drinks =  {
    'coke': 'Coke',
    'pepsi': 'Pepsi',
    'lemonade': 'Lemonade'
   };
   var yourDrink = drinks[type];
   return yourDrink;
}
EDIT to make it more clear, here's the steps to get to the example code:

Replace the temp yourDrink var:

JavaScript code:
function getDrink(type) {
    var drinks =  {
    'coke': 'Coke',
    'pepsi': 'Pepsi',
    'lemonade': 'Lemonade'
   };
   /*
   var yourDrink = drinks[type];
   return yourDrink;
   */
   return drinks[type]; 
}
Replace the temp drinks var:

JavaScript code:

function getDrink(type) {
   /*
    var drinks =  {
    'coke': 'Coke',
    'pepsi': 'Pepsi',
    'lemonade': 'Lemonade'
   };
   var yourDrink = drinks[type];
   return yourDrink;
   */
   return  {
    'coke': 'Coke',
    'pepsi': 'Pepsi',
    'lemonade': 'Lemonade'
   }[type]; 
}

Lumpy fucked around with this message at 17:16 on Dec 11, 2014

Raskolnikov2089
Nov 3, 2006

Schizzy to the matic

Lumpy posted:

JavaScript code:

function getDrink(type) {
   /*
    var drinks =  {
    'coke': 'Coke',
    'pepsi': 'Pepsi',
    'lemonade': 'Lemonade'
   };
   var yourDrink = drinks[type];
   return yourDrink;
   */
   return  {
    'coke': 'Coke',
    'pepsi': 'Pepsi',
    'lemonade': 'Lemonade'
   }[type]; 
}


Thank you, that was exactly what was throwing me off. Seeing the longer version made it a lot more clear. I think I'll skip going that route until I'm more familiar with objects.

loquacius
Oct 21, 2008

So, I'm making a tablet version of a webpage, and I was running into an issue where the page is already partly zoomed in upon load, at different zoom levels depending on whether the tablet is in portrait or landscape mode. I added some javascript to the orientation-change handler to alter the initial-scale value on the viewport meta to scale the page to the correct level, and it works perfectly EXCEPT that when an iOS Safari user rotates from landscape to portrait mode the page is slightly off-center (as in the left edge of it is off the left edge of the screen) until they scroll. For the life of me I can't find any information on viewport adjustments making a page load off-center, so I don't know how to address this. Anybody have the slightest idea what I'm talking about or am I just babbling? It's been a long week.

e: To clarify, post-viewport-adjustment the page is the correct size, but part of it is slightly off the screen.

loquacius fucked around with this message at 21:36 on Dec 12, 2014

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

loquacius posted:

So, I'm making a tablet version of a webpage, and I was running into an issue where the page is already partly zoomed in upon load, at different zoom levels depending on whether the tablet is in portrait or landscape mode. I added some javascript to the orientation-change handler to alter the initial-scale value on the viewport meta to scale the page to the correct level, and it works perfectly EXCEPT that when an iOS Safari user rotates from landscape to portrait mode the page is slightly off-center (as in the left edge of it is off the left edge of the screen) until they scroll. For the life of me I can't find any information on viewport adjustments making a page load off-center, so I don't know how to address this. Anybody have the slightest idea what I'm talking about or am I just babbling? It's been a long week.

e: To clarify, post-viewport-adjustment the page is the correct size, but part of it is slightly off the screen.

Is this in the HEAD of your page?

code:
<meta name="viewport" content="width=device-width, initial-scale=1">
If not, put it there and get rid of your JS. If it's already there, then I got nothing w/o seeing your page.

BlueInkAlchemist
Apr 17, 2012

"He's also known as 'BlueInkAlchemist'."
"Who calls him that?"
"Himself, mostly."
What are good/the best resources for an ActionScript developer like myself switching over to JavaScript? A lot of positions are open where I can get in as long as my code doesn't entirely suck.

waffle enthusiast
Nov 16, 2007



I think I'm having a bit of trouble getting my head around the proper way to do async callbacks in Node/Express. I've got the following awful code, that I want to basically query a third-party server, parse the HTML into JSON, and return it via the Express API (I'll eventually cache this data in Redis or something). The async nature of Node is kind of screwing me up:

code:
// file: server/api/du/du.controller.js
var _ = require('lodash');
var request = require('request');
var cheerio = require('cheerio');

// Return a JSON object of times/dates that I parsed out
exports.index = function(req, res) {
  res.json([getDuData()]);
};

// make a request and parse the HTML.
// return the parsed response.
function getDuData() {
  console.log("Fetching DU data");

  var request_url = 'http://denveruniv-web.ungerboeck.com/coe/coe_p1_all.aspx?oc=01&cc=ICEDI30';
  var dropInData = {};

  request(request_url, function (error, response, html) {
    // snipped, parse a bunch of HTML w/ Cheerio
    dropInData = response;
  });

  return dropInData;
};
This code always returns the empty JSON via the API: [{}]

However, if I log the results of the request call to the console, I see it later sets dropInData to the parsed HTML, after the request finishes. So, it definitely appears the code is happily skipping over the async request call and returning an empty JSON object like it should. But how should I make the server wait for the third party request to finish?

Adbot
ADBOT LOVES YOU

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Dangerllama posted:

I think I'm having a bit of trouble getting my head around the proper way to do async callbacks in Node/Express. I've got the following awful code, that I want to basically query a third-party server, parse the HTML into JSON, and return it via the Express API (I'll eventually cache this data in Redis or something). The async nature of Node is kind of screwing me up:

code:
// file: server/api/du/du.controller.js
var _ = require('lodash');
var request = require('request');
var cheerio = require('cheerio');

// Return a JSON object of times/dates that I parsed out
exports.index = function(req, res) {
  res.json([getDuData()]);
};

// make a request and parse the HTML.
// return the parsed response.
function getDuData() {
  console.log("Fetching DU data");

  var request_url = 'http://denveruniv-web.ungerboeck.com/coe/coe_p1_all.aspx?oc=01&cc=ICEDI30';
  var dropInData = {};

  request(request_url, function (error, response, html) {
    // snipped, parse a bunch of HTML w/ Cheerio
    dropInData = response;
  });

  return dropInData;
};
This code always returns the empty JSON via the API: [{}]

However, if I log the results of the request call to the console, I see it later sets dropInData to the parsed HTML, after the request finishes. So, it definitely appears the code is happily skipping over the async request call and returning an empty JSON object like it should. But how should I make the server wait for the third party request to finish?

Phone posting, so no code, but use a library like async: https://github.com/caolan/async

There will be examples that do exactly what you are looking for.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply