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
Subjunctive
Sep 12, 2006

✨sparkle and shine✨

ES6 finalized the modules spec a while back, and various transpilers like Traceur let you use the syntax ahead of direct browser support. But yeah, browsers will implement ES6.

Adbot
ADBOT LOVES YOU

Kekekela
Oct 28, 2004

Thermopyle posted:

What's the plan on module support in the browser? How's that going to work?

I mean, I know how to do it right now with something like webpack or browserify, but I assume eventually browsers will support doing something with the import keyword.

This is the eventual syntax (sorry if that's not what you were asking) :

http://www.2ality.com/2014/09/es6-modules-final.html


e: oh you wanted browser implementation details, um, uh, erm...

Kekekela fucked around with this message at 10:39 on Jul 24, 2015

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.
I just can't wrap my head around promises. Does anyone have a fool proof tutorial/explanation?

geeves
Sep 16, 2004

Knifegrab posted:

I just can't wrap my head around promises. Does anyone have a fool proof tutorial/explanation?

I've been reading through these books - https://github.com/getify/You-Dont-Know-JS

Here's the book & chapter that discusses Promises:

https://github.com/getify/You-Dont-Know-JS/blob/master/async%20&%20performance/ch3.md

Edit: Hopefully that helps. I'm probably in the same boat as you. I won't see more benefits until I see more real world examples.

geeves fucked around with this message at 20:40 on Jul 23, 2015

Dr. Poz
Sep 8, 2003

Dr. Poz just diagnosed you with a serious case of being a pussy. Now get back out there and hit them till you can't remember your kid's name.

Pillbug

Knifegrab posted:

I just can't wrap my head around promises. Does anyone have a fool proof tutorial/explanation?

I found this blog post to be great as it covers some of the common misuses of Promises and does a good job of illustrating the pitfalls. After reading the blog I began following Nolan Lawson on twitter and it is both cool and good.

http://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html

qntm
Jun 17, 2009

Dr. Poz posted:

I found this blog post to be great as it covers some of the common misuses of Promises and does a good job of illustrating the pitfalls. After reading the blog I began following Nolan Lawson on twitter and it is both cool and good.

http://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html

quote:

Q: What is the difference between these four promises?

JavaScript code:
doSomething().then(function () {
  return doSomethingElse();
});

doSomething().then(function () {
  doSomethingElse();
});

doSomething().then(doSomethingElse());

doSomething().then(doSomethingElse);
If you know the answer, then congratulations: you're a promises ninja. You have my permission to stop reading this blog post.

For the other 99.99% of you, you're in good company. Nobody who responded to my tweet could solve it

Hah, this is a pretty tricksy question but I douby anybody in the world could fit the right answer into a reply tweet.

Thermopyle
Jul 1, 2003

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

Subjunctive posted:

ES6 finalized the modules spec a while back, and various transpilers like Traceur let you use the syntax ahead of direct browser support. But yeah, browsers will implement ES6.

Yeah, I've been using babel with browserify and the import/export syntax for months now. My real question is what this will look like when the browser implements it. I guess it just fires off a request each time it hits an import statement so we don't have to do the current bundling step?

spacebard
Jan 1, 2007

Football~

Thermopyle posted:

Yeah, I've been using babel with browserify and the import/export syntax for months now. My real question is what this will look like when the browser implements it. I guess it just fires off a request each time it hits an import statement so we don't have to do the current bundling step?

I think any improvements will depend on browser and server HTTP 2 support, which if I understand it correctly, allows to stream multiple files per request.

bartkusa
Sep 25, 2005

Air, Fire, Earth, Hope

spacebard posted:

I think any improvements will depend on browser and server HTTP 2 support, which if I understand it correctly, allows to stream multiple files per request.

HTTP 2 can't fix this by itself, because it's still lovely to wait for file X to download before requesting file Y.

If anything, the build step will be MORE complicated because the web server itself will need to understand the dependency graph in order to push it, instead of just the JS bundler.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
There's been talk and perhaps a spec floating around to bundle some sort of giant requirement list in native HTML5/ES6 like this though.

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.

Dr. Poz posted:

I found this blog post to be great as it covers some of the common misuses of Promises and does a good job of illustrating the pitfalls. After reading the blog I began following Nolan Lawson on twitter and it is both cool and good.

http://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html

Thank you, reading through this blog post now, hopefully it helps!

geeves posted:

I've been reading through these books - https://github.com/getify/You-Dont-Know-JS

Here's the book & chapter that discusses Promises:

https://github.com/getify/You-Dont-Know-JS/blob/master/async%20&%20performance/ch3.md

Edit: Hopefully that helps. I'm probably in the same boat as you. I won't see more benefits until I see more real world examples.

I read through a few different parts of the different books to see how I felt about this author and I like it so much I just ordered every book he had off amazon on paperback. Thanks guys, I am a pretty amateur JS developer, but I am working for the big boys now and my chops definitely need to improve!

obstipator
Nov 8, 2009

by FactsAreUseless
What's a good resource for teaching people async programming? I've tried explaining it a dozen times over the past few weeks to my underlings but it's just not sticking and I feel like I'm gonna go insane.

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

obstipator posted:

What's a good resource for teaching people async programming? I've tried explaining it a dozen times over the past few weeks to my underlings but it's just not sticking and I feel like I'm gonna go insane.

I'm too tired to work this into a coherent example but gather them all in the kitchen and send them one at a time to fetch things. Then send them all at once for things. Then send some people and give others instructions that rely on the objects being retrieved by the currently running threads/people.

also try thinking about them as humans beings rather than lings

Bhaal
Jul 13, 2001
I ain't going down alone
Dr. Infant, MD
That works for getting the gist of race conditions and stuff for the truly uninitiated, but to me the largest hurdle for people (esp. in a js context) isn't understanding that concept but rather having the sensitivity to notice when something is async or not. To me that is what trips people up far more than getting how a callback or promise works. They can follow a contrived example and get it, but in practice they are just misidentifying many non-blocking call as blocking. Typically that boils down to just learning to be vigilant to the specifics of what a function call is going to do, and breaking it down to either i/o or in-memory-only (a coarse but generally applicable guideline for determining if something is blocking or not).

As for suggestions, if they get the fundamentals, maybe scour up some code snippets with some that correctly catch async behavior and some that do not (stackexchange should be rife with both) , and have them quiz themselves on being able to tell whether snippet B is correctly written or not, if not where is the race condition, how to fix, etc...

Thermopyle
Jul 1, 2003

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

Like... what is an example of a non-blocking call that someone who can program computers misidentified as blocking?

Bhaal
Jul 13, 2001
I ain't going down alone
Dr. Infant, MD
Most recently I've seen it with file i/o and gulp, specifically. Like doing some stream/pipe/dest chain and then assuming the output file will be there and ready for usage downstream in the main execution line of the gulp task or wherever. On a local build you may not notice the problem because you aren't minifying and taking extra steps that a production build would, so the files ends up being ready in time just by chance, and/or a version of it already existed on your local so you don't get errors.

Maybe what I mean is more that if you're a developer who isn't seasoned to think about async consequences all the time, and you're dealing with an async call that manipulates state in one area*, then it makes for an easy trap to forget/overlook that when trying to access the same piece of state in another area.

* Or worse, have those calls wrapped such that no callback or .then is required to use the wrapper, probably due to another unseasonsed developer who thought they were being tidy and helpful by "containing" the async call

obstipator
Nov 8, 2009

by FactsAreUseless

Bhaal posted:

That works for getting the gist of race conditions and stuff for the truly uninitiated, but to me the largest hurdle for people (esp. in a js context) isn't understanding that concept but rather having the sensitivity to notice when something is async or not. To me that is what trips people up far more than getting how a callback or promise works. They can follow a contrived example and get it, but in practice they are just misidentifying many non-blocking call as blocking. Typically that boils down to just learning to be vigilant to the specifics of what a function call is going to do, and breaking it down to either i/o or in-memory-only (a coarse but generally applicable guideline for determining if something is blocking or not).

As for suggestions, if they get the fundamentals, maybe scour up some code snippets with some that correctly catch async behavior and some that do not (stackexchange should be rife with both) , and have them quiz themselves on being able to tell whether snippet B is correctly written or not, if not where is the race condition, how to fix, etc...

Ohhhhhh, that makes a lot of sense that they understand the concept but can't easily acknowledge which functions are async without spending extra time looking it back over. Thanks. Makes me feel better since I thought my explanations on async were going partially ignored, and since I'm working with nodejs--async at its finest..--there's many more opportunities to misinterpret non-blocking as blocking.

Gazpacho
Jun 18, 2004

by Fluffdaddy
Slippery Tilde

obstipator posted:

What's a good resource for teaching people async programming? I've tried explaining it a dozen times over the past few weeks to my underlings but it's just not sticking and I feel like I'm gonna go insane.
If someone has prior experience with thread-based concurrency and wants to move over to JavaScript's model, they really really really should read Lauer & Needham's "On the Duality of Operating System Structures." (or you should read it and turn it into a presentation.)

Gazpacho fucked around with this message at 00:04 on Aug 3, 2015

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.
I hate promises and callbacks. I just cannot get my dumb head around them, I feel hopeless and lost, and I've read almost every resource I can find on it.

I have a simple problem, I am writing in node, I have a postgres database. I want to use pg package to return the results of a query. I want to do this async using promises. But I honestly don't even know where to begin or how to do it. It seems like the pg's query function is blocking, so can I just not use promises with it? I honestly am so confused. My brain is so bad at async.

Gazpacho
Jun 18, 2004

by Fluffdaddy
Slippery Tilde
Why do you believe that pg's query function is blocking? Do you have a small code sample that you believe demonstrates that?

e: As someone who gets by at writing asynchronous JS when absolutely necessary, I will confirm that it's an exceptional PITA, and I would never tell someone that they suck just because they've missed some fine points of scope and callback-threading.

Gazpacho fucked around with this message at 03:42 on Aug 8, 2015

Vulture Culture
Jul 14, 2003

I was never enjoying it. I only eat it for the nutrients.

Knifegrab posted:

I hate promises and callbacks. I just cannot get my dumb head around them, I feel hopeless and lost, and I've read almost every resource I can find on it.

I have a simple problem, I am writing in node, I have a postgres database. I want to use pg package to return the results of a query. I want to do this async using promises. But I honestly don't even know where to begin or how to do it. It seems like the pg's query function is blocking, so can I just not use promises with it? I honestly am so confused. My brain is so bad at async.
Promises are for async code, not for sync code. (You can technically use them with sync code, but why?)

If you suck at async code, you either suck at modeling the flow of the problem you're trying to solve, or you suck at doing something with the state you get back. Once you stop leaking state all over the place, it just becomes a way of decomposing your flow into different chains that execute at the same time. It might help if you flowchart the path of remote data through your program. If nothing else, it can help us write some boilerplate code for you to start with.

Think of a promise like a box that might have a value inside. When you do something (.then()) on the resolution of the promise, you're basically saying:

  • If this box already has a value stored in it, do this thing immediately.
  • Otherwise, do this thing as soon as the box has a value stored in it.

There's nothing crazy or complicated about that, the promise chain is just some code sequence sitting around until someone dumps a value in the box.

Kekekela
Oct 28, 2004
disclaimer: I'm a novice with promises but I work in some pretty promise heavy code-bases so it was vital to my sanity that I comprehend them somewhat

Knifegrab posted:

It seems like the pg's query function is blocking, so can I just not use promises with it?


When you say its blocking, do you mean from a logical standpoint the program can't continue until the query is complete?
If so then then I think the "You're Missing the Point of Promises" section here will probably be useful. I know you said you've read all the resources, but this may be extremely on point I think. It really helped me reframe promises in my head as "callback aggregator thinger..." to providing the correspondence between synch and async functions he describes in that gist:

Domenic Denicola posted:

The thing is, promises are not about callback aggregation. That's a simple utility. Promises are about something much deeper, namely providing a direct correspondence between synchronous functions and asynchronous functions.

What does this mean? Well, there are two very important aspects of synchronous functions:

* They return values
* They throw exceptions
Both of these are essentially about composition. That is, you can feed the return value of one function straight into another, and keep doing this indefinitely. More importantly, if at any point that process fails, one function in the composition chain can throw an exception, which then bypasses all further compositional layers until it comes into the hands of someone who can handle it with a catch.

Now, in an asynchronous world, you can no longer return values: they simply aren't ready in time. Similarly, you can't throw exceptions, because nobody's there to catch them. So we descend into the so-called "callback hell," where composition of return values involves nested callbacks, and composition of errors involves passing them up the chain manually, and oh by the way you'd better never throw an exception or else you'll need to introduce something crazy like domains.

The point of promises is to give us back functional composition and error bubbling in the async world.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Knifegrab posted:

I hate promises and callbacks. I just cannot get my dumb head around them, I feel hopeless and lost, and I've read almost every resource I can find on it.

I have a simple problem, I am writing in node, I have a postgres database. I want to use pg package to return the results of a query. I want to do this async using promises. But I honestly don't even know where to begin or how to do it. It seems like the pg's query function is blocking, so can I just not use promises with it? I honestly am so confused. My brain is so bad at async.

If you don't want to think about it, use pg-promise and there you go.

EDIT: https://github.com/vitaly-t/pg-promise/wiki/Learn-by-Example might be helpful as well.

EDIT the 2nd: There's another super simple library: https://github.com/coderhaoxin/pg-then/blob/master/index.js that you can read through the source to see how they do it, and maybe that will help you wrap your head around promises a bit.

Lumpy fucked around with this message at 20:52 on Aug 8, 2015

Kobayashi
Aug 13, 2004

by Nyc_Tattoo
Speaking of promises and async modeling in general, how do I handle a situation where I want to report aggregate statistics? For example, say I have an array of URLs and I use Node's request module to grab them. Aside from global state, how do I accumulate e.g. the total size or the total number of links or whatever? It's not clear how to "wait" for a bunch of async calls to complete and do something with all the results, or to incrementally build up a result as the async calls complete.

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.



Kobayashi posted:

Speaking of promises and async modeling in general, how do I handle a situation where I want to report aggregate statistics? For example, say I have an array of URLs and I use Node's request module to grab them. Aside from global state, how do I accumulate e.g. the total size or the total number of links or whatever? It's not clear how to "wait" for a bunch of async calls to complete and do something with all the results, or to incrementally build up a result as the async calls complete.

Use Promise.all([...]) to get a new promise that resolves when all of your promises resolve, then just wait on that promise as you normally would with a list of your final values.

Kobayashi
Aug 13, 2004

by Nyc_Tattoo

piratepilates posted:

Use Promise.all([...]) to get a new promise that resolves when all of your promises resolve, then just wait on that promise as you normally would with a list of your final values.

Hmm, OK, that was the nudge I needed. It seems like promises are an all or nothing thing -- either the whole code should use them or nothing will ever make sense.

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.



Kobayashi posted:

Hmm, OK, that was the nudge I needed. It seems like promises are an all or nothing thing -- either the whole code should use them or nothing will ever make sense.

You can still use standard async control with promises (after all, a promise is just an object you attach a callback to on completion), it's just that the promises-way tends to work out just as good or better than not using them.

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.

Kekekela posted:

disclaimer: I'm a novice with promises but I work in some pretty promise heavy code-bases so it was vital to my sanity that I comprehend them somewhat


When you say its blocking, do you mean from a logical standpoint the program can't continue until the query is complete?
If so then then I think the "You're Missing the Point of Promises" section here will probably be useful. I know you said you've read all the resources, but this may be extremely on point I think. It really helped me reframe promises in my head as "callback aggregator thinger..." to providing the correspondence between synch and async functions he describes in that gist:

OK I will try to make up some assumptions about promises and the code I want to write, I will admit I am probably wrong.

- The standard PG library is blocking because the request function does not contain a callback in its paramaters, so since its not utilizing callbacks, its a sync function not async.
- Promises only work when used with async functions already.
- However I also am under the impression that promises are a good way to keep a system from being bogged down by blocking requests (such as a slow SQL request).

I literally want to take a single file of code, connect to my database (a util file I already have) and just do one request to a table in postgres like this: "select * from config.chapters". But I want to do it in promises without using any extra extensions.

I guess I am just confused as to how to wrap something in a promise or how to start a promise off. I just hate promises.

Vulture Culture
Jul 14, 2003

I was never enjoying it. I only eat it for the nutrients.

Knifegrab posted:

I guess I am just confused as to how to wrap something in a promise or how to start a promise off. I just hate promises.
If you need to interact with a library which does not natively support promises, then most promise implementations like when.js or Bluebird or whatever contain a lift() function which takes as a parameter a (possibly Node-style) function and wraps that function to return a promise instead. So instead of

code:
mymodule.myfunction(a, b, c, function (err, data) {
    if (err) {
        // handle error
    } else {
        // do something
    }
});
you have

code:
node = require('when/node');
myfunction = node.lift(mymodule.myfunction);
return myfunction(a, b, c)
    .then(function () {
        // do something
    })
    .otherwise(function () {
        // handle error
    });

Vulture Culture fucked around with this message at 19:02 on Aug 10, 2015

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.

Vulture Culture posted:

If you need to interact with a library which does not natively support promises, then most promise implementations like when.js or Bluebird or whatever contain a lift() function which takes as a parameter a (possibly Node-style) function and wraps that function to return a promise instead. So instead of

code:
mymodule.myfunction(a, b, c, function (err, data) {
    if (err) {
        // handle error
    } else {
        // do something
    }
});
you have

code:
node = require('when/node');
myfunction = node.lift(mymodule.myfunction);
return myfunction(a, b, c)
    .then(function () {
        // do something
    })
    .otherwise(function () {
        // handle error
    });

Would it be possible to get this example but within the q library which is the library I am working in?

Bhaal
Jul 13, 2001
I ain't going down alone
Dr. Infant, MD

Knifegrab posted:

OK I will try to make up some assumptions about promises and the code I want to write, I will admit I am probably wrong.

- The standard PG library is blocking because the request function does not contain a callback in its paramaters, so since its not utilizing callbacks, its a sync function not async.
I'm not sure which library you're referring to. Do you have a link to it? I looked at a few node / pg libs and they all seemed to take a callback arg. If the one you're looking at doesn't, then it might have promises baked in and what it's returning is a promise, and is therefore non-blocking.

quote:

- Promises only work when used with async functions already.
Not really, and this might be a source of confusion. Promises can work on any function. You can take: function (a,b) { return a+b} or function () {return "hello!"} and wrap each of them into a promise.

The intention of a promise is to take your function, run it, and box up two things about it: (1) when it finishes and (2) what it returns. Then the promise object is attached to that metaphorical box and returned to the caller. The caller will then call things like .then which will attach further events of what to do with the your function's return value (and that's where the async part gets put in). When your function is ready (ie. that "box" has the when & what components of your function satisfied) the function in .then will be triggered to run. The fact that your a+b function will be ready immediately (because it already ran) is insignificant to the promise object. It still goes through all the motions and it just so happens that as soon as .then is ready it gets executed right away.

Now, when a function you call returns the actual value you're looking for, a promise can wrap it directly like with a+b above. However when your function requires a callback of its own, in order to behave the same way, the promise object needs to attach its own callback (a deferred object, which has its own internal promise which is what gets returned in the main thread of execution). From the promise object's perspective, it is saying "Look, your function doesn't directly return the value you're looking for and it does not signify that it is completed. Instead it is the _callback_ that gets passed to your function that we're interested in, so let's give it my own callback and I'll now use that as my trigger for when you function is both finished and has a return value that we're interested in". This of course ends up being the most typical use case because wrapping a+b is generally pretty silly (but it can be done, and might be a helpful exercise in demystifying what promises are actually doing).

quote:

- However I also am under the impression that promises are a good way to keep a system from being bogged down by blocking requests (such as a slow SQL request).
Not really, on two counts. First, using our a+b example, if we instead had some crazy nested loops of dummy addition that took forever to execute, it would be both blocking and take a long time, and the promise structure wouldn't be ready until it finishes anyway so our main thread of code would be blocking just as much (because we are executing the nested loops directly in the main thread). There are ways to wrangle something like that into an async process (and you could use promise structures to do so) but that's not really the intended usage of promises. Secondly, I doubt the pg library is blocking. DB interaction, file i/o, user input and network requests in general can all be assumed to be asynchronous in js.

quote:

I literally want to take a single file of code, connect to my database (a util file I already have) and just do one request to a table in postgres like this: "select * from config.chapters". But I want to do it in promises without using any extra extensions.

I guess I am just confused as to how to wrap something in a promise or how to start a promise off. I just hate promises.
code:
var pg = require ("my-pg-lib")
var q = require("q")

// example one: your pg lib returns a promise -- no q needed!
pg.query("select * from config.chapters")
	.then( function (rows) {
		console.log(rows) // we should see the data from config.chapters in the console
	})

// example two: your pg lib requires callbacks, so we'll invoke q to handle that poo poo and will assume it's the node callback convention
// Note: it is usually a practice to instead wrap these into a function and "return deferred.promise" instead.
var deferred = q.defer()
pg.query("select * from config.chapters", deferred.makeNodeResolver())
deferred.promise.then(function (rows){
		console.log (rows) // db data!
	)}

NOTE: I left out pretty much any discussion about error handlers and so on, just to make the explanations and examples simpler, but those are of course a necessity.

(EDIT: left some var declarations out, coffeescript is great but leads to bad habits)

Bhaal fucked around with this message at 20:00 on Aug 10, 2015

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.

Bhaal posted:

I'm not sure which library you're referring to. Do you have a link to it? I looked at a few node / pg libs and they all seemed to take a callback arg. If the one you're looking at doesn't, then it might have promises baked in and what it's returning is a promise, and is therefore non-blocking.
Not really, and this might be a source of confusion. Promises can work on any function. You can take: function (a,b) { return a+b} or function () {return "hello!"} and wrap each of them into a promise.

The intention of a promise is to take your function, run it, and box up two things about it: (1) when it finishes and (2) what it returns. Then the promise object is attached to that metaphorical box and returned to the caller. The caller will then call things like .then which will attach further events of what to do with the your function's return value (and that's where the async part gets put in). When your function is ready (ie. that "box" has the when & what components of your function satisfied) the function in .then will be triggered to run. The fact that your a+b function will be ready immediately (because it already ran) is insignificant to the promise object. It still goes through all the motions and it just so happens that as soon as .then is ready it gets executed right away.

Now, when a function you call returns the actual value you're looking for, a promise can wrap it directly like with a+b above. However when your function requires a callback of its own, in order to behave the same way, the promise object needs to attach its own callback (a deferred object, which has its own internal promise which is what gets returned in the main thread of execution). From the promise object's perspective, it is saying "Look, your function doesn't directly return the value you're looking for and it does not signify that it is completed. Instead it is the _callback_ that gets passed to your function that we're interested in, so let's give it my own callback and I'll now use that as my trigger for when you function is both finished and has a return value that we're interested in". This of course ends up being the most typical use case because wrapping a+b is generally pretty silly (but it can be done, and might be a helpful exercise in demystifying what promises are actually doing).
Not really, on two counts. First, using our a+b example, if we instead had some crazy nested loops of dummy addition that took forever to execute, it would be both blocking and take a long time, and the promise structure wouldn't be ready until it finishes anyway so our main thread of code would be blocking just as much (because we are executing the nested loops directly in the main thread). There are ways to wrangle something like that into an async process (and you could use promise structures to do so) but that's not really the intended usage of promises. Secondly, I doubt the pg library is blocking. DB interaction, file i/o, user input and network requests in general can all be assumed to be asynchronous in js.

code:
pg = require ("my-pg-lib")
q = require("q")

// example one: your pg lib returns a promise -- no q needed!
pg.query("select * from config.chapters")
	.then( function (rows) {
		console.log(rows) // we should see the data from config.chapters in the console
	})

// example two: your pg lib requires callbacks, so we'll invoke q to handle that poo poo
// Note: it is usually a practice to instead wrap these into a function and "return deferred.promise" instead.
var deferred = q.defer()
pg.query("select * from config.chapters", deferred.makeNodeResolver())
deferred.promise.then(function (rows){
		console.log (rows) // db data!
	)}

NOTE: I left out pretty much any discussion about error handlers and so on, just to make the explanations and examples simpler, but those are of course a necessity.

Thank you so much, this helps a lot. I just looekd up teh PG library I am using, it is here: https://github.com/brianc/node-postgres/wiki/Client

I am assuming since there are no references to promises being returned, that htis library does not return a promise upon executing the query method. However I do now see that the query method does accept an optional callback. So would you second example of code be most appropriate?

Secondly, if a function or method does not return a promise, or take a callback in its parameters, how would I tie it into a promise?

Finally in your example, where:
code:
deferred.promise.then(function (rows){
I am assuming rows is the return value of the query method? I thought a .then was supposed to have two functions, the success and reject? Is the reject optional and if only one function is present it assumes it to be the success function?

bartkusa
Sep 25, 2005

Air, Fire, Earth, Hope

Knifegrab posted:

Finally in your example, where:
code:
deferred.promise.then(function (rows){
I am assuming rows is the return value of the query method? I thought a .then was supposed to have two functions, the success and reject? Is the reject optional and if only one function is present it assumes it to be the success function?

Yes, "rows" is the return value of the query method.

Also, .then can have one or two functions. The first one is the success function, and the second one (if it exists) is the error-handling function. It's optional, kind of like how functions don't have to handle exceptions, and can trust their callers to handle them.


Knifegrab posted:

Would it be possible to get this example but within the q library which is the library I am working in?

Just use Q(...).

code:
var value = 1;
var promise = Q(value); // Returns a promise that's already resolved with the value 1.

bartkusa fucked around with this message at 20:57 on Aug 10, 2015

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.

bartkusa posted:

Yes, "rows" is the return value of the query method.

Also, .then can have one or two functions. The first one is the success function, and the second one (if it exists) is the error-handling function. It's optional, kind of like how functions don't have to handle exceptions, and can trust their callers to handle them.


Just use Q(...).

code:
var value = 1;
var promise = Q(value); // Returns a promise that's already resolved with the value 1.

"rows" in this case can be called anything correct? So the value of rows is determined as what would normally be the result var in callback(result,[err]) that makeNodeResolver takes over correct?

necrotic
Aug 2, 2005
I owe my brother big time for this!

Knifegrab posted:

"rows" in this case can be called anything correct? So the value of rows is determined as what would normally be the result var in callback(result,[err]) that makeNodeResolver takes over correct?

Yes, "rows" is just the name of your argument for that function. It can be "iDontGetThisShit" if you want. Also yes to your second question.

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.

necrotic posted:

Yes, "rows" is just the name of your argument for that function. It can be "iDontGetThisShit" if you want. Also yes to your second question.

iDontGetThisShit is a good variable name for all of my variables as they relate to Promises.

But thanks for the help guys, I was able to get a query up and running utlizing promises in Q. Thanks for all your help, I do sort of get it now!

Bhaal
Jul 13, 2001
I ain't going down alone
Dr. Infant, MD
Honestly they take a 70/30 mixture of practice and reading to really have it all sort of click. Most of my "ah-ha" moments came from discovering & tracking down race conditions that snuck up on me after I thought I had done everything correctly. But to get there you have to build something big enough with all the little app-specific complexities and so on that your code ends up being more than just a handful example snippets cribbed from the internet. But that way you at least will have some substantial code to tinker and troubleshoot with.

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.
Proud to say I got my first file up and running utilizing promises! Thanks for everyones help, I am really starting to understand it now. I do have one more question.

When I am chaining my promises together, my promises look something like this:

function1()
.then(function2)
.then(function3)
.done();

For example. However what if I wanted to pass function 2 or function 3 parameters? How would I do that? Right now I am just utilizing global parameters, which works, but I feel like maybe its not the best thing to do?

piratepilates
Mar 28, 2004

So I will learn to live with it. Because I can live with it. I can live with it.



Knifegrab posted:

Proud to say I got my first file up and running utilizing promises! Thanks for everyones help, I am really starting to understand it now. I do have one more question.

When I am chaining my promises together, my promises look something like this:

function1()
.then(function2)
.then(function3)
.done();

For example. However what if I wanted to pass function 2 or function 3 parameters? How would I do that? Right now I am just utilizing global parameters, which works, but I feel like maybe its not the best thing to do?

Make a function that returns a function that will be used as a callback in a promise:

code:
function makeFarts(fartsParameter) {
    return function fartsPromiseCallback(fartsValue) {
        console.log(`poop: ${fartsParameter}, balls: ${fartsValue}`);
    }
}

Promise.resolve('test')
.then(makeFarts('farts'));

Adbot
ADBOT LOVES YOU

Vulture Culture
Jul 14, 2003

I was never enjoying it. I only eat it for the nutrients.
There's a few other (simpler) ways you can do this.

Using bind():

code:
function1()
    .then(function2.bind(this, 'someArg', 9000))
    .then(function3)
    .done();
Using anonymous functions:

code:
function1()
    .then(function () {
        return function2('someArg', 9000);
    })
    .then(function3)
    .done();

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