Joe Joe - 21 days ago 9
MySQL Question

Multiple Verifications on Mysql ExpressJS NodeJS

I'm new in NodeJS and i'm working on ExpressJS in an API for use it with angular2

I have the next problem: I need do checks in db (mysql) before make an insert and can handle the errors correctly... my ugly code is:

http://pastebin.com/iuBMhUeb

And it doesn't work, becouse it execute the insert ignoring the verify(s) ...

Any help or suggestion will be appreciated

Answer

Welcome to Asynchronous Javascript, friend!

All your connection.query methods are actually running at the same time, because they are asynchronous functions. This is something you're going to have to get used to, along with callbacks. As a result, none of your "check" queries have actually finished before the "insert" queries begin.

You will have to define the precise order which your functions have to follow, and then use the Async library accordingly (look for Async.series, Async.parallel and Async.waterfall).

Asynchronous JS can be tough to grasp at first, but can do wonders on your response time once you get the hang of it.

Comments