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
Ranzear
Jul 25, 2013

Nolgthorn posted:

You want something like this. To avoid hoisting and save you some sanity, plz use `let` and `const` instead of `var`. Super easier.

They're forcing jquery on 'im, I'd half expect them to not have let and const support.

Adbot
ADBOT LOVES YOU

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Man these classes using old javascript make me feel like Javascript is the new PHP.

With all of these alternate old ways of doing things, that are still supported, that you're not supposed to use, that are taught in classes. I can see learning programming in school to start, but if I had taken a class for everything I wanted to know I'd have never made it anywhere.

Coco Rodreguiz
Jan 12, 2007

Peckerhead isn't used enough as an insult if you ask me.

Skandranon posted:

Imagine you want to encapsulate some code that does something for you. Specifically, calculate PI. Lets call that getPI().
That function might look something like "function getPI() { return 3.14; }". What this means, is if you then call it, you will get the value from the return statement. So you can do "var pi = getPI();". Now pi = 3.14. You can also pass information into functions. So you could do like "function getArea(radius) { return getPI() * radius * radius; }". You would call it like "var area = getArea(3)".



Nolgthorn posted:

code:
    var a = password();
    var b = parseAscii(a);
    var c = parseBin(b);
    var d = split(c);

    forEach(d);
You want something like this. To avoid hoisting and save you some sanity, plz use `let` and `const` instead of `var`. Super easier.

Christ this is what I needed. A simple example that explains what a return does, and a "for your code this is what you have wrong. This is an outline for how it should go".

Thank you guys so much. I've been so frustrated with how this class explains poo poo.

Ranzear
Jul 25, 2013

Coco Rodreguiz posted:

Thank you guys so much. I've been so frustrated with how this class explains poo poo.

Yeah, there are a few red flags about that class, least of which is jquery when they can't even teach you what return does.

Also there's nothing wrong with:
code:
foreach(split(parseBin(parseAscii(password()))));
It's only ugly because you have all those split up in the first place and the real way to clean it up is OOP.

Ranzear fucked around with this message at 03:17 on Oct 8, 2017

Dogcow
Jun 21, 2005

Coco Rodreguiz posted:

Can someone help me out here? I'm taking a JavaScript class and I hosed this assignment up enough it dropped me a letter grade but I'm still not 100% on what I did wrong.

It's supposed to prompt you for a letter (and the instructor wants everything pirate themed :shrug:). Then eventually write that to the page with true or false for each 0 or 1.

I know I'm not grasping some simple js concept cause I'm a loving idiot. Apparently I'm not calling the function right but I dunno why but the way the instructor and ta explain it to me I just can't comprehend. This is the first assignment that needed returns and I feel like I'm not grasping what a return does correctly too.


tldr: help me I'm stupid at JavaScript and if I can't grasp calling a function and returns I'm probably gonna fail every assignment for the rest of the semester.

Your instructor is bad and I hope you didn't spend too much on this course because this code they gave you is real bad and completely broken. I genuinely don't know where you are at in terms of learning how to code generally so if any of this sounds condescending please don't take it that way. I was totally where you are 10 years ago and would've killed for an explanation like this. Really, I promise, I'm quite dumb, it took me a long time to grasp any semi complex code.

It is complicated, despite what any goon spergs might say, but believe me, if my dumb rear end can learn it anyone can.

So here is my heavily commented version of what you posted:

JavaScript code:
function getPassword() {
	// Your instructor is here trying (but failing) to use something called "Hungarian Notation"
  // ([url]https://en.wikipedia.org/wiki/Hungarian_notation[/url]) for these variable names. This notation means
  // that when the variable is an integer (a whole number) it's name should start with 'int'.
  // I say they are failing at this because clearly all of these variables are strings
  // (sequences of alphanumeric characters), not integers.
  var intDefLetter = "C";
  var intQuestion = "Arrr I got a message I can give, do ye have the password?";
	var intNewLetter = "";

	// This is a very obscure and totally unused feature built in to web browsers that displays a dialog box
  // that allows the user to enter input ([url]https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt[/url]).
  // It will (for some reason) display a 'C' in the dialog box as the default input because of the
  // variable above (intDefLetter).
  intNewLetter = prompt(intQuestion, intDefLetter);

	// This checks whether the user has entered more than one letter in the dialog box mentioned above,
  // and if they did then it opens the same dialog box again.
	if (intNewLetter.length > 1) {
  	prompt(intQuestion, intDefLetter);
  }

	// This returns whatever was last entered in the dialog box from this function.
	return intNewLetter;
}

// Every character that can be entered via the keyboard can be represented by a number and the number for
// each character (in this function) is determined by a protocol called ASCII ([url]https://en.wikipedia.org/wiki/ASCII[/url])
// which is why the this function is named 'parseASCII' however it is extremely dumb because you can simply use
// 'charCodeAt' in your own code any time so this function is pointless.
// For example:
// var intASCIICodeOfA = "A".charCodeAt(0);
function parseAscii(intNewLetter) {
	var intAscii = "";
	intAscii = intNewLetter.charCodeAt(0);

	return intAscii;
}

function parseBin(intAscii) {
	// Here again your instructor is trying to use Hungarian Notation and they are at least somewhat more successful
  // this time. This variable name is supposed to be an abbreviation for "string binary". There is no such thing so
  // again that's why I say they are still unsuccessful. Really this variable is, again, just a string.
  var strBin = "";

	// This finds the base two ([url]https://en.wikipedia.org/wiki/Binary_number[/url]) representation of the ASCII code
  // (which is an integer) of the character entered by the user in the dialog box originally.
	strBin = parseInt(intAscii, 10).toString(2);

	// Here the idea is to create a byte ([url]https://en.wikipedia.org/wiki/Byte[/url]) from the base two (binary) representation
  // of the ASCII code derived above from the character that the user entered in the dialog box.
 
  // This loop is required because a byte is eight bits (a bit is a one or a zero) long. Therefore if the base two
  // representation of the character entered is less than eight characters we need to add enough characters that we
  // can create a byte (get up to eight bits).
  if (strBin.length < 8) {
    var intPlaceHolders = 8 - strBin.length;	// This determines how many characters we have to add to have a byte.

    for (var i = 0; i < intPlaceHolders; i++) {
      strBin = "0" + strBin;	// Add a zero on to the 'front' of the string.
    }             
  }

  return strBin;	// Return the string that represents the byte.
}

// Here again, bizzarely, your instructor is pointlessly wrapping a standard built in Javascript function available
// everywhere in your own code with another function. You can simply call "split" on any string any time in your code.
// The split function is called on a string and splits it into multiple strings (inside an array) at every point that
// the separator you send exists, for example:
// var arrayFromAString = "one,two,three".split(','); // returns an array with three elements: ['one', 'two', 'three']
function split(strBin) {
	var strMessage = "";

  strMessage = strBin.split("");  

  return strMessage;
}

// Your instructor has a truly weird habit of writing new functions named identically to existing built in
// (to the browser environment) Javascript functions. The 'forEach' function exists in the prototype of the Array
// object ([url]https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach[/url]).
function forEach(strMessage) {
  var arrayLength = strMessage.length;
  var i;

	for (i = 0; i < arrayLength; i++) {
  	// THE FOLLOWING IS COMPLETELY BROKEN: it's supposed to read "strMessage[0] == 0" which would determine if the first
    // character in the passed string (strMessage) is zero, however what this code actually does is always return the Boolean value
    // 'false' because it is making the first character of the passed string zero. Whenever you assign a value to a variable using
    // the equals operator ("=") that expression returns the assigned value which in this case is a zero and a zero in Javascript
    // is "falsy" ([url]https://developer.mozilla.org/en-US/docs/Glossary/Falsy[/url]) meaning it will evaluate to the Boolean value 'false'.
    // This means that this block of code will never execute.
  	if (strMessage[i] = 0) {
  		var falseOutput = document.getElementById("message"); 
    	var msgFalse = "False ";     

      falseOutput.textContent = msgFalse;
    // This block of code will always execute (see comment above).
  	} else {
    	// This is simply finding the part of the webpage this code is executing on with the ID "message" and placing the text "True "
      // inside of that element. As noted above this code is basically broken so this will happen no matter which single character is
      // entered in the initial dialog box.
			var trueOutput = document.getElementById("message");
  		var msgTrue = "True ";

 	    trueOutput.textContent = msgTrue;
    }
  }
}

// I have renamed these functions to make some kind of sense.
var password = getPassword();
var ASCIIPassword = parseAscii(password);
var binaryStrPassword = parseBin(ASCIIPassword);
var splitBinaryPassword = split(binaryStrPassword);
forEach(splitBinaryPassword);
There's a website called JSFiddle where you can easily run any Javascript code you want. I've used a feature of that website here in this working version of the code in order to avoid having to use the jQuery "on load" function because it is irrelevant and unecessary to what you are learning here.

Dogcow fucked around with this message at 05:39 on Oct 8, 2017

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
code:
    // This is a very obscure and totally unused feature built in to web browsers that displays a dialog box
  // that allows the user to enter input ([url]https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt[/url]).
  // It will (for some reason) display a 'C' in the dialog box as the default input because of the
  // variable above (intDefLetter).
  intNewLetter = prompt(intQuestion, intDefLetter);

    // This checks whether the user has entered more than one letter in the dialog box mentioned above,
  // and if they did then it opens the same dialog box again.
    if (intNewLetter.length > 1) {
  	prompt(intQuestion, intDefLetter);
  }
What if I enter more than one character 2 times? Also, the second prompt doesn't store the value so it doesn't matter at all what I type.

code:
let newLetter = '';

while (newLetter.length !== 1) {
  newLetter = prompt(question, 'C');
}

Nolgthorn fucked around with this message at 17:48 on Oct 8, 2017

Dogcow
Jun 21, 2005

Nolgthorn posted:

code:
    // This is a very obscure and totally unused feature built in to web browsers that displays a dialog box
  // that allows the user to enter input ([url]https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt[/url]).
  // It will (for some reason) display a 'C' in the dialog box as the default input because of the
  // variable above (intDefLetter).
  intNewLetter = prompt(intQuestion, intDefLetter);

    // This checks whether the user has entered more than one letter in the dialog box mentioned above,
  // and if they did then it opens the same dialog box again.
    if (intNewLetter.length > 1) {
  	prompt(intQuestion, intDefLetter);
  }

What if I enter more than one character 2 times? Also, the second prompt doesn't store the value so it doesn't matter at all what I type.

Yep, it is totally broken that way too. The second prompt does nothing. I'm also assuming it's suppose to be a while loop (while intNewLetter.length > 1) so you have to enter a single letter to continue.. but who knows.

Roadie
Jun 30, 2013
And here's a quick idea of what all that code looks like in a saner world, using all the relevant built-ins and chucking unnecessary stuff:

JavaScript code:
/**
 * Show the user a prompt and get exactly n letters from it.
 * @param {number} desiredLength
 * @return {string}
 */
function getPassword(desiredLength) {
  const defaultLetter = "C";
  const question = "Arrr I got a message I can give, do ye have the password?";
  let newLetter = "";

  while (newLetter.length !== desiredLength) {
    newLetter = prompt(question, defaultLetter);
  }

  return newLetter;
}

/**
 * Take a number and return the binary string representation of it. Assumes that
 * the number is at most 128 (the upper end of the ASCII range). This will break
 * if given the char code of a letter with diacritics or other special stuff!
 * @example ```js
 *   console.log(parseBin(92)); // logs "01011100"
 * ```
 * @param {number} charCode
 * @return {string}
 */
function charCodeToBinaryString(charCode) {
  const binaryString = parseInt(charCode, 10).toString(2);
  return "0".repeat(8 - binaryString.length) + binaryString;
}

/**
 * Given an array of "1" and "0" values, change the text of the `#message`
 * element on the page based on each one.
 * @example ```js
 *   checkBinaryString(["1", "0", "1", "0"]); // `#message` will end up `false`
 * ```
 * @param {string[]} binaryString
 * @param {HTMLElement} outputElement
 */
function checkBinaryString(binaryString, outputElement) {
  binaryString.forEach(value => {
    outputElement.textContent = value === "0" ? "False" : "True";
  });
}

/**
 * @param {HTMLElement} outputElement
 */
function getAndParsePassword(outputElement) {
  const password = getPassword(1);
  const ASCIIPassword = password.charCodeAt(0);
  const binaryStrPassword = charCodeToBinaryString(ASCIIPassword);
  const splitBinaryPassword = binaryStrPassword.split("");

  checkBinaryString(splitBinaryPassword, outputElement);
}

getAndParsePassword(document.getElementById("message"));
General notes:

The annotations before each function aren't necessary, but some editors (for example: Visual Studio Code, available free) will use them to automatically check that what you're doing with parameters and return values is right and will show you errors if you do something wrong (e.g. returning a number on a function marked with a string return), as well as supplying documentation popups when you reference one function somewhere else. Javascript stuff generally uses JSDoc, but there's very similar stuff for other languages.

As already mentioned, const ("this value never never changes")/let ("this value can change") are generally better to use than var because of annoying, complicated reasons with scope (var does different weird legacy things based on where you use it, while const/let always act consistently). However, it does depend on having a more-or-less modern browser that supports them properly.

Triple equals (===) are almost always better than double equals (==), because double equals will implicitly convert different types, which results in assorted weird dumb stuff. For example, 0 == "0", null == undefined, and 0 == new String("0") are all true. This may seem convenient at first, but it inevitably sets something on fire when one function or another accepts bad input because of it.

Arrow functions (using the value => { whatever } format instead of function (value) { whatever } format inside the forEach) are super convenient both for their shorter syntax, and because they fix some weird legacy issues with this. For now you don't really need to worry about that, but the short explanation is that with normal function declarations, if you ever need to use the special this value from the outside on the inside, you need to do weird workarounds; with an arrow function, the this on the inside is automatically the same as the this on the outside. However, like const/let, you need to be using a browser that supports them. (One catch: If you have more than one param, you need to write it like (param1, param2) => { whatever } instead.)

Ternary if statements (x === y ? whatHappensIfTrue : whatHappensIfFalse) are super useful for small inline stuff. Don't overuse them because it can make your code nigh unreadable, but since you can use them inline (unlike normal if statements), for cases like this it's an easy way to simplify things that would otherwise be identical except for a single value. Some other languages (like Ruby) treat even a normal if statement as an inline value and so don't have anything like a ternary if.

Edit:

And for funsies, the minimalist version:

JavaScript code:
const LENGTH = 1
const DEFAULT_ANSWER = 'C'
const QUESTION = 'Arrr I got a message I can give, do ye have the password?'

/**
 * Show the user a prompt and get exactly `length` letters from it.
 * @param {number} length
 * @param {string} defaultAnswer
 * @param {string} question
 * @return {string}
 */
function getLetter(length, defaultAnswer, question) {
  const letter = prompt(question, defaultLetter)
  return letter.length === length
    ? letter
    : getLetter(length, defaultAnswer, question)
}

/**
 * Return the last bit of the given letter.
 * @param {string} letter
 * @return {0 | 1}
 */
const lastBitFromLetter = letter => letter.charCodeAt(0) & 0x1

// Set the message according to the last bit
document.getElementById('message').textContent =
  lastBitFromLetter(getLetter(LENGTH, DEFAULT_ANSWER, QUESTION)) === 0
    ? 'False'
    : 'True'
Don't you just love bitwise operations?

Roadie fucked around with this message at 21:08 on Oct 8, 2017

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Dude not even God himself understands bitwise operations.

Joda
Apr 24, 2010

When I'm off, I just like to really let go and have fun, y'know?

Fun Shoe

Roadie posted:

Don't you just love bitwise operations?

In a strongly typed language I try to not use them, but don't mind them, since behaviour is well-defined. In one where types are more of a hint than an instruction, I tend to avoid them like the plague. There's a massive difference between the char '1', the int 1 and the float 1.0, and I have no idea where or when JS might decide it needs to use on or the other.

Doom Mathematic
Sep 2, 2008
Assuming that you are working with a JavaScript number - i.e. a 64-bit float - bitwise operators (potentially lossily) convert/cast/truncate all of their operands to signed 32-bit integers prior to operation, and (losslessly now) convert the result back to a JavaScript number to return.

E: Do not perform bitwise operations on non-numbers and then complain about the results.

huhu
Feb 24, 2006
What am I missing here?

In React, I have a component that receives props, calls an ajax request on those props with componentDidUpdate(), and then sets the state after the ajax request is done. I see that I've created an infinite loop but I'm not sure how to stop it. Thoughts?

geeves
Sep 16, 2004

huhu posted:

What am I missing here?

In React, I have a component that receives props, calls an ajax request on those props with componentDidUpdate(), and then sets the state after the ajax request is done. I see that I've created an infinite loop but I'm not sure how to stop it. Thoughts?

It's not a react problem, but it's time to refactor and figure out calls in an order that's sane. Not always easy, but in cases like this, it's so you don't end up with circular logic.

prom candy
Dec 16, 2005

Only I may dance

huhu posted:

What am I missing here?

In React, I have a component that receives props, calls an ajax request on those props with componentDidUpdate(), and then sets the state after the ajax request is done. I see that I've created an infinite loop but I'm not sure how to stop it. Thoughts?

Compare this.props to prevProps (first argument to componentDidUpdate) to see if you actually got new props and need to re-call the endpoint

plasticbugs
Dec 13, 2006

Special Batman and Robin

Ranzear posted:

code:

ranzear@ubuntu:~$ php -a
Interactive mode enabled

php > echo iconv("UTF-8", "ASCII//TRANSLIT", "Beyoncé");
Beyonce
php >
Weird.

The PHP docs note that it may be system dependent. I copypasted your 'Beyoncé' but maybe yours is a composite character and it's doing the diacritic separately? Are you missing 'UTF-8' as the first arg?

I was using an iconv node module and was calling it identically to what you have there with the same parameters. Was getting that odd apostrophe, so I went towards a more brute force solution which strips all diacritics from text and replaces them with their standard ascii counterpart. Your suggestion for storing searchable text was right on the money. I'm sure I'll use that pattern elsewhere if I bump up against a similar issue.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

prom candy posted:

Compare this.props to prevProps (first argument to componentDidUpdate) to see if you actually got new props and need to re-call the endpoint

Possibly the better approach is to do the compare on componentWillReceiveProps rather than DidUpdate, and WillReceiveProps does not trigger on internal state updates, whereas DidUpdate does.

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself

Osmosisch posted:

Heads up for those still using bower: they are advising you to gtfo.

Yeah this is pretty funny. I was just applying to a job that listed bower as a requirement and then went to bower's homepage where it says to just use yarn.

I was p much thinking "....wait what?"

prom candy
Dec 16, 2005

Only I may dance

Maluco Marinero posted:

Possibly the better approach is to do the compare on componentWillReceiveProps rather than DidUpdate, and WillReceiveProps does not trigger on internal state updates, whereas DidUpdate does.

Very true yeah, I was assuming componentDidUpdate was being used on purpose but if not then use componentWillReceiveProps. In that case your first arg is nextProps (the incoming props) instead of prevProps.

Thermopyle
Jul 1, 2003

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

I always prefer code where intent is very explicit so I avoid bitwise operations.

Munkeymon
Aug 14, 2003

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



Nolgthorn posted:

code:
let newLetter = '';

while (newLetter.length !== 1) {
  newLetter = prompt(question, 'C');
}

Try that with an emoji

tricksnake
Nov 16, 2012
What kind of things can I make with Javascript? Besides boring front-end crap?

porksmash
Sep 30, 2008
With Node.js you can make anything.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

tricksnake posted:

What kind of things can I make with Javascript? Besides boring front-end crap?

Boring games, boring mobile apps, boring desktop apps,, boring back-end crap: a whole world of boring crap is open to you with JavaScript.

Ranzear
Jul 25, 2013

tricksnake posted:

What kind of things can I make with Javascript? Besides boring front-end crap?
Example of boring crap: https://caliber.online

I really should get going on Boats Game already.

Edit: Some older crap, pre-WebAudio: https://caliber.online/SuperTanks.htm
The things I did to have stereo sound...

Ranzear fucked around with this message at 18:22 on Oct 9, 2017

Joda
Apr 24, 2010

When I'm off, I just like to really let go and have fun, y'know?

Fun Shoe
Not sure if this is the right thread to ask this, but if I compile some C++ to webassembly and am using multithreading (e.g. std::thread, std::future etc.) will that execute on multiple threads, or is webassembly stuck with one thread like JS? If so, to get parallel execution when compiling with gcc for native execution I have to add the compiler flag -pthread to get mutexes and such to act like they're supposed to, do I have to do something similar for webassembly compilation?

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
The Unity3D game engine used to be a modified version of javascript. But, you can use it for all kinds of cool stuff due to the callstack and singlethreadedness.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.
Guess who's back back back?

I am doing some promises mixed with some piping and binding and I am trying something with a try catch but the promise is not catching it and it is saying its an unhandled error. Not sure why:

code:

Q.fcall(function() {

    //code

    sendResponse();

    function sendResponse() {
        
        const transformer = transform((record, callback) => {
            try {
                let jsonRecord = JSON.stringify(record.map((acc, cell, i) => acc[colDefs[i].id] = cell), {});
            } catch (e) {
                throw new Error("Improperly formatted response data");
            }
            
            callback(null, jsonRecord);
        });


        proc.stdout.pipe(transformer).pipe(res);
    }
})
.fail((err) => handleErrors(req, res, err))
.done();

So ignoring why it might catch an error or what might be causing an error, why isn't my code approprietly handling this error I throw in the .fail portion of the promise chain?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Knifegrab posted:

Guess who's back back back?

I am doing some promises mixed with some piping and binding and I am trying something with a try catch but the promise is not catching it and it is saying its an unhandled error. Not sure why:

code:

Q.fcall(function() {

    //code

    sendResponse();

    function sendResponse() {
        
        const transformer = transform((record, callback) => {
            try {
                let jsonRecord = JSON.stringify(record.map((acc, cell, i) => acc[colDefs[i].id] = cell), {});
            } catch (e) {
                throw new Error("Improperly formatted response data");
            }
            
            callback(null, jsonRecord);
        });


        proc.stdout.pipe(transformer).pipe(res);
    }
})
.fail((err) => handleErrors(req, res, err))
.done();

So ignoring why it might catch an error or what might be causing an error, why isn't my code approprietly handling this error I throw in the .fail portion of the promise chain?

My guess would be proc.stdout or that transform function that is defin d somewhere else catching it instead, but I don't know what the non-standard stuff Q is doing with fcall and fail so I can't be sure. For fun, throw on the first line of sendResponse.

That code seems... odd as well. Many nested functions is generally a code smell, but again, I don't know Q.

Roadie
Jun 30, 2013

Knifegrab posted:

So ignoring why it might catch an error or what might be causing an error, why isn't my code approprietly handling this error I throw in the .fail portion of the promise chain?

The throw is getting eaten by the multiple nested function definitions. You need to refactor it.

I also don't understand why you're using promises, since I don't see anything async there. Plus, if you're going to use promises, you should use real promises, not the Q library (unless you're totally stuck with it for legacy reasons).

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

Roadie posted:

The throw is getting eaten by the multiple nested function definitions. You need to refactor it.

I also don't understand why you're using promises, since I don't see anything async there. Plus, if you're going to use promises, you should use real promises, not the Q library (unless you're totally stuck with it for legacy reasons).

Sorry so there is async stuff above but that is cut out for brevity, this is pretty far into the promise chain.

I've also replaced teh stupid Q poo poo with real promises now.

Knifegrab fucked around with this message at 19:39 on Oct 9, 2017

MrMoo
Sep 14, 2000

Joda posted:

Not sure if this is the right thread to ask this, but if I compile some C++ to webassembly and am using multithreading (e.g. std::thread, std::future etc.) will that execute on multiple threads, or is webassembly stuck with one thread like JS? If so, to get parallel execution when compiling with gcc for native execution I have to add the compiler flag -pthread to get mutexes and such to act like they're supposed to, do I have to do something similar for webassembly compilation?

Multi-threading is supposed to be landing this monthyear 🤞 around Chrome 63.

https://wasmdash.appspot.com

Kinda meh page:

https://github.com/WebAssembly/threads

MrMoo fucked around with this message at 20:27 on Oct 9, 2017

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.
code:
doAsyncStuff()  //return a promise (gently caress q)
.then(() => {

    //code

    sendResponse();

    function sendResponse() {
        
        const transformer = transform((record, callback) => {
            try {
                let jsonRecord = JSON.stringify(record.map((acc, cell, i) => acc[colDefs[i].id] = cell), {});
            } catch (e) {
                throw new Error("Improperly formatted response data");
            }
            
            callback(null, jsonRecord);
        });

        transformer.on('error', (err) => {
            throw new Error(err);
        });


        proc.stdout.pipe(transformer).pipe(res);
    }
})
.fail((err) => handleErrors(req, res, err))
.done();
Changed it to this but it is still saying that it is an unhandled error. I am quite confused by this.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Knifegrab posted:

code:
doAsyncStuff()  //return a promise (gently caress q)
.then(() => {

    //code

    sendResponse();

    function sendResponse() {
        
        const transformer = transform((record, callback) => {
            try {
                let jsonRecord = JSON.stringify(record.map((acc, cell, i) => acc[colDefs[i].id] = cell), {});
            } catch (e) {
                throw new Error("Improperly formatted response data");
            }
            
            callback(null, jsonRecord);
        });

        transformer.on('error', (err) => {
            throw new Error(err);
        });


        proc.stdout.pipe(transformer).pipe(res);
    }
})
.fail((err) => handleErrors(req, res, err))
.done();
Changed it to this but it is still saying that it is an unhandled error. I am quite confused by this.

First off: fail is not a thing in promises. Use catch.
Secondly: your logic is still confusing and has many places where an exception could get squashed.

Do this:

code:
doAsyncStuff()
.then( () => throw "buttes" )
.catch( e => console.error( e ) )
That will tell you if your exception is happening in the async thing or not. If you only catch buttes (lol) then you know your nested function soup is to blame for it not being handled.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Once you get it working move the `throw 'buttes'` into the catch block since you know it'll never get thrown again anyway.

ROFLburger
Jan 12, 2006

Knifegrab posted:

code:
doAsyncStuff()  //return a promise (gently caress q)
.then(() => {

    //code

    sendResponse();

    function sendResponse() {
        
        const transformer = transform((record, callback) => {
            try {
                let jsonRecord = JSON.stringify(record.map((acc, cell, i) => acc[colDefs[i].id] = cell), {});
            } catch (e) {
                throw new Error("Improperly formatted response data");
            }
            
            callback(null, jsonRecord);
        });

        transformer.on('error', (err) => {
            throw new Error(err);
        });


        proc.stdout.pipe(transformer).pipe(res);
    }
})
.fail((err) => handleErrors(req, res, err))
.done();
Changed it to this but it is still saying that it is an unhandled error. I am quite confused by this.

Looking at the docs for your promise library, .fail(failureHandler) is just a shortcut for doing .then(iDontCareAboutThisSuccessHandler, failurehandler)

Since you're using .then(successhandler), it doesn't looks like your subsequent .fail is going to be invoked unless the successHandler in your .then returns another [rejected] "Q" promise

You could either add a failureHandler callback to your .then (after your existing successHandler, or add a .catch after the .then

ROFLburger fucked around with this message at 21:43 on Oct 9, 2017

Odette
Mar 19, 2011

porksmash posted:

With Node.js you can make anything.

Yeah; apart from an actual OS (don't even think about trying to create NodeRTOS! :ohdear:), the sky's the limit.

Roadie
Jun 30, 2013

Knifegrab posted:

Changed it to this but it is still saying that it is an unhandled error. I am quite confused by this.

Your errors are still getting eaten by your inner function scope. Don't do that, it's silly.

JavaScript code:
const transformer = transform =>
  transform((record, callback) => {
    try {
      let jsonRecord = JSON.stringify(
        record.map((acc, cell, i) => (acc[colDefs[i].id] = cell)),
        {}
      )

      callback(null, jsonRecord)
    } catch (e) {
      throw new Error('Improperly formatted response data')
    }
  })

doAsyncStuff()
  .then(() => {
    // code

    thisTransformer = transformer(transform)
    transformer.on('error', err => {
      throw new Error(err)
    })

    try {
      proc.stdout.pipe(thisTransformer).pipe(res)
    } catch (e) {
      throw e
    }
  })
  .catch(err => handleErrors(req, res, err))

Rosalind
Apr 30, 2013

When we hit our lowest point, we are open to the greatest change.

I am very, very new to using Javascript and sometimes have to write little snippets for my workplace. I am trying to have a function that reads something from the url and then uses it to pass along some info in a url when the participant clicks on a link. The code I wrote works on most modern web browsers but I just had someone testing the website out come back to me and say that on their iPhone 5 with Safari they got an error message. This is the code:

code:
function getCity() {
    var cityurl = document.referrer;
    var citystart = cityurl.search("city=");
    var city = "0";
    if (citystart > 0) {
        var city = cityurl.substring(citystart + 5);
    }
    var link = "(a website url)?City=" + city;
    window.open(link);
}
Am I doing anything obviously wrong that would affect an older browser?

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Mobile safari is very unpredictable. You are defining the city variable twice, you only need to define it the first time.

code:
function getCity() {
    var cityurl = document.referrer;
    var citystart = cityurl.search("city=");
    var city = "0";
    if (citystart > 0) {
        city = cityurl.substring(citystart + 5);
    }
    var link = "(a website url)?City=" + city;
    window.open(link);
}
Not sure that will fix it.

Adbot
ADBOT LOVES YOU

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Rosalind posted:

I am very, very new to using Javascript and sometimes have to write little snippets for my workplace. I am trying to have a function that reads something from the url and then uses it to pass along some info in a url when the participant clicks on a link. The code I wrote works on most modern web browsers but I just had someone testing the website out come back to me and say that on their iPhone 5 with Safari they got an error message. This is the code:

code:
function getCity() {
    var cityurl = document.referrer;
    var citystart = cityurl.search("city=");
    var city = "0";
    if (citystart > 0) {
        var city = cityurl.substring(citystart + 5);
    }
    var link = "(a website url)?City=" + city;
    window.open(link);
}
Am I doing anything obviously wrong that would affect an older browser?

Mobile Safari does not pass the referrer header, so that's why it does not work.

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