Wednesday 11 January 2017

I'm confused about how to use promises to query a postgres database. Looking for advice!

Hey guys,for a new little project, I thought I'd use promises for my database-related stuff, as it seems to become the new standard - I have never used promises before though! I use PostgreSQL and pg-promise. My basic understanding is, that instead of having subsequent queries in nested callbacks, the queries will be chained one after the other. But I don't understand fully how that works.I have the following code in a /register route of a server:db.one("SELECT EXISTS(SELECT 1 FROM users WHERE name=$1) AS 'exists'", [name]) .then(function(data) { if(data.exists) { res.json({ "success": false, "flag": "name_taken" }); } else { //TODO: insert new user } }).catch(function(error) { next(error); }); The first query checks whether the user name is available, and now I have to integrate a second query, that insert the new user. I am confused, about how that should be done. Shoud I:chain a second .then() and do the query inside of thator: execute the query inside the first .then(), and return the resulting data, subsequently handling it in a second .then()Or ar both of these wrong?Any advice appreciated ;)

Submitted January 11, 2017 at 04:49PM by DJLaMeche

No comments:

Post a Comment