NodeJS MySQL query in loop returning before intented
I am trying to create a function that would generate 4 unique id (hexadecimal) to insert into my database. I put the query inside a do while loop to check for collision, if the code is already present, I regenerate the code, if not, I return the value.
The problem is that the loop exits before intended. For example if the code 'a' is generated but already presented in the database, the code gets regenerated but the loop exits and a new query never gets made. The new code does not get returned - instead the first code that was generated is returned.
Here's my code:
const FIND_EXISITNG_COURT =
"SELECT access_code,team1,team2 FROM courts WHERE access_code= ?";
function generateAccessCode() {
var random = Math.floor(Math.random() * (+30 - +0)) + +0;
var code = random.toString(16);
var hasDupe = false;
do {
connection.query(FIND_EXISITNG_COURT, [code], (err, results) => {
if (err) {
throw err;
} else if (results.length > 0) {
random = Math.floor(Math.random() * (+30 - +0)) + +0;
code = random.toString(16);
hasDupe = true;
} else {
hasDupe = false;
}
});
} while (hasDupe);
return code;
}
I am new to NodeJS so I don't know if it's bad practice to do this. Any help would be much appreciated!
javascript mysql node.js
add a comment |
I am trying to create a function that would generate 4 unique id (hexadecimal) to insert into my database. I put the query inside a do while loop to check for collision, if the code is already present, I regenerate the code, if not, I return the value.
The problem is that the loop exits before intended. For example if the code 'a' is generated but already presented in the database, the code gets regenerated but the loop exits and a new query never gets made. The new code does not get returned - instead the first code that was generated is returned.
Here's my code:
const FIND_EXISITNG_COURT =
"SELECT access_code,team1,team2 FROM courts WHERE access_code= ?";
function generateAccessCode() {
var random = Math.floor(Math.random() * (+30 - +0)) + +0;
var code = random.toString(16);
var hasDupe = false;
do {
connection.query(FIND_EXISITNG_COURT, [code], (err, results) => {
if (err) {
throw err;
} else if (results.length > 0) {
random = Math.floor(Math.random() * (+30 - +0)) + +0;
code = random.toString(16);
hasDupe = true;
} else {
hasDupe = false;
}
});
} while (hasDupe);
return code;
}
I am new to NodeJS so I don't know if it's bad practice to do this. Any help would be much appreciated!
javascript mysql node.js
You have a sync problem. Your loop will run and not wait for the inner-function call to return. The most easy solution is to make the loop recursive inside the connection.query function
– split
Nov 20 '18 at 5:30
add a comment |
I am trying to create a function that would generate 4 unique id (hexadecimal) to insert into my database. I put the query inside a do while loop to check for collision, if the code is already present, I regenerate the code, if not, I return the value.
The problem is that the loop exits before intended. For example if the code 'a' is generated but already presented in the database, the code gets regenerated but the loop exits and a new query never gets made. The new code does not get returned - instead the first code that was generated is returned.
Here's my code:
const FIND_EXISITNG_COURT =
"SELECT access_code,team1,team2 FROM courts WHERE access_code= ?";
function generateAccessCode() {
var random = Math.floor(Math.random() * (+30 - +0)) + +0;
var code = random.toString(16);
var hasDupe = false;
do {
connection.query(FIND_EXISITNG_COURT, [code], (err, results) => {
if (err) {
throw err;
} else if (results.length > 0) {
random = Math.floor(Math.random() * (+30 - +0)) + +0;
code = random.toString(16);
hasDupe = true;
} else {
hasDupe = false;
}
});
} while (hasDupe);
return code;
}
I am new to NodeJS so I don't know if it's bad practice to do this. Any help would be much appreciated!
javascript mysql node.js
I am trying to create a function that would generate 4 unique id (hexadecimal) to insert into my database. I put the query inside a do while loop to check for collision, if the code is already present, I regenerate the code, if not, I return the value.
The problem is that the loop exits before intended. For example if the code 'a' is generated but already presented in the database, the code gets regenerated but the loop exits and a new query never gets made. The new code does not get returned - instead the first code that was generated is returned.
Here's my code:
const FIND_EXISITNG_COURT =
"SELECT access_code,team1,team2 FROM courts WHERE access_code= ?";
function generateAccessCode() {
var random = Math.floor(Math.random() * (+30 - +0)) + +0;
var code = random.toString(16);
var hasDupe = false;
do {
connection.query(FIND_EXISITNG_COURT, [code], (err, results) => {
if (err) {
throw err;
} else if (results.length > 0) {
random = Math.floor(Math.random() * (+30 - +0)) + +0;
code = random.toString(16);
hasDupe = true;
} else {
hasDupe = false;
}
});
} while (hasDupe);
return code;
}
I am new to NodeJS so I don't know if it's bad practice to do this. Any help would be much appreciated!
javascript mysql node.js
javascript mysql node.js
edited Nov 20 '18 at 5:52
Auralieas
asked Nov 20 '18 at 5:14
AuralieasAuralieas
84
84
You have a sync problem. Your loop will run and not wait for the inner-function call to return. The most easy solution is to make the loop recursive inside the connection.query function
– split
Nov 20 '18 at 5:30
add a comment |
You have a sync problem. Your loop will run and not wait for the inner-function call to return. The most easy solution is to make the loop recursive inside the connection.query function
– split
Nov 20 '18 at 5:30
You have a sync problem. Your loop will run and not wait for the inner-function call to return. The most easy solution is to make the loop recursive inside the connection.query function
– split
Nov 20 '18 at 5:30
You have a sync problem. Your loop will run and not wait for the inner-function call to return. The most easy solution is to make the loop recursive inside the connection.query function
– split
Nov 20 '18 at 5:30
add a comment |
2 Answers
2
active
oldest
votes
In your code, Callback function of query
will be run later when the data has been ready, so hasDupe
will be false
at first time and generated code will be return.
You can use Promise
and async
function to solve your problem
const FIND_EXISITNG_COURT =
"SELECT access_code,team1,team2 FROM courts WHERE access_code= ?";
function selectByCode(code) {
return new Promise((resolve, reject) => {
connection.query(FIND_EXISITNG_COURT, [code], (err, results) => {
if (err) {
reject(err);
} else {
resolve(results.length)
}
});
}
async function generateAccessCode() {
var random = Math.floor(Math.random() * (+30 - +0)) + +0;
var code = random.toString(16);
var hasDupe = false;
let count =0;
try{
do {
count = await selectByCode(code);
if (count > 0) {
random = Math.floor(Math.random() * (+30 - +0)) + +0;
code = random.toString(16);
hasDupe = true;
} else {
hasDupe = false;
}
} while (hasDupe);
return code;
}
catch(e){
throw e;
}
}
This works great! Thank you so much :)
– Auralieas
Nov 20 '18 at 6:17
add a comment |
Your call to connection.query
is asynchronous, meaning the callback you've defined does not run right away. Your code just registers that callback and then keeps on executing until the end of generateAccessCode
. The callback doesn't get called until much later (when the db returns something) so hasDupe
gets set only long after the original function has already exited.
You basically have 3 options to handle this: callbacks, promises, or async/await (which is really just syntactic sugar on top of promises).
An example using async/await but trying to keep as close to your original structure as I can (run it more than once to see it working):
// this is a mock for the db call. This "database" already holds records with IDs 0, 2 and 3.
// IRL you will need to wrap your db call in a function that returns a promise
// if you want to do it this way
const connectionQuery = function (code) {
return new Promise((resolve) => {
setTimeout(() => resolve(code === 1 ? : [true]), 1000);
});
}
async function generateAccessCode() {
// simplified the code generation for this example
let code = Math.floor(Math.random() * 4); // Code can be 0, 1, 2, or 3
let hasDupe = false;
let results;
do {
results = await connectionQuery(code); // await here is the key
if (results.length > 0) {
console.log(`Code ${code} already exists in the database. Generating new code...`);
code = Math.floor(Math.random() * 4);
hasDupe = true;
} else {
hasDupe = false;
}
} while (hasDupe);
return code;
}
generateAccessCode()
.then((code) => {
console.log(`Final result: ${code}`);
})
.catch((err) => {
console.log(err);
});
Using callbacks instead:
// this is a mock for the db call. This "database" already holds records with IDs 0, 2 and 3.
const connectionQuery = function (code, callback) {
setTimeout(() => {
callback(null, code === 1 ? : [true]);
}, 1000);
}
function generateAccessCode(callback) {
// simplified the code generation for this example
let code = Math.floor(Math.random() * 4); // Code can be 0, 1, 2, or 3
let hasDupe = false;
let results;
connectionQuery(code, (err, results) => {
if (err) {
return callback(err);
}
if (results.length) {
console.log(`Code ${code} already exists in the DB`);
return generateAccessCode(callback);
}
callback(null, code);
});
}
generateAccessCode((err, code) => {
console.log(`Final result: ${code}`);
});
Thank you for all the code examples! Definitely learned more about asynchronous functions and how to handle them.
– Auralieas
Nov 20 '18 at 6:18
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53386621%2fnodejs-mysql-query-in-loop-returning-before-intented%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
In your code, Callback function of query
will be run later when the data has been ready, so hasDupe
will be false
at first time and generated code will be return.
You can use Promise
and async
function to solve your problem
const FIND_EXISITNG_COURT =
"SELECT access_code,team1,team2 FROM courts WHERE access_code= ?";
function selectByCode(code) {
return new Promise((resolve, reject) => {
connection.query(FIND_EXISITNG_COURT, [code], (err, results) => {
if (err) {
reject(err);
} else {
resolve(results.length)
}
});
}
async function generateAccessCode() {
var random = Math.floor(Math.random() * (+30 - +0)) + +0;
var code = random.toString(16);
var hasDupe = false;
let count =0;
try{
do {
count = await selectByCode(code);
if (count > 0) {
random = Math.floor(Math.random() * (+30 - +0)) + +0;
code = random.toString(16);
hasDupe = true;
} else {
hasDupe = false;
}
} while (hasDupe);
return code;
}
catch(e){
throw e;
}
}
This works great! Thank you so much :)
– Auralieas
Nov 20 '18 at 6:17
add a comment |
In your code, Callback function of query
will be run later when the data has been ready, so hasDupe
will be false
at first time and generated code will be return.
You can use Promise
and async
function to solve your problem
const FIND_EXISITNG_COURT =
"SELECT access_code,team1,team2 FROM courts WHERE access_code= ?";
function selectByCode(code) {
return new Promise((resolve, reject) => {
connection.query(FIND_EXISITNG_COURT, [code], (err, results) => {
if (err) {
reject(err);
} else {
resolve(results.length)
}
});
}
async function generateAccessCode() {
var random = Math.floor(Math.random() * (+30 - +0)) + +0;
var code = random.toString(16);
var hasDupe = false;
let count =0;
try{
do {
count = await selectByCode(code);
if (count > 0) {
random = Math.floor(Math.random() * (+30 - +0)) + +0;
code = random.toString(16);
hasDupe = true;
} else {
hasDupe = false;
}
} while (hasDupe);
return code;
}
catch(e){
throw e;
}
}
This works great! Thank you so much :)
– Auralieas
Nov 20 '18 at 6:17
add a comment |
In your code, Callback function of query
will be run later when the data has been ready, so hasDupe
will be false
at first time and generated code will be return.
You can use Promise
and async
function to solve your problem
const FIND_EXISITNG_COURT =
"SELECT access_code,team1,team2 FROM courts WHERE access_code= ?";
function selectByCode(code) {
return new Promise((resolve, reject) => {
connection.query(FIND_EXISITNG_COURT, [code], (err, results) => {
if (err) {
reject(err);
} else {
resolve(results.length)
}
});
}
async function generateAccessCode() {
var random = Math.floor(Math.random() * (+30 - +0)) + +0;
var code = random.toString(16);
var hasDupe = false;
let count =0;
try{
do {
count = await selectByCode(code);
if (count > 0) {
random = Math.floor(Math.random() * (+30 - +0)) + +0;
code = random.toString(16);
hasDupe = true;
} else {
hasDupe = false;
}
} while (hasDupe);
return code;
}
catch(e){
throw e;
}
}
In your code, Callback function of query
will be run later when the data has been ready, so hasDupe
will be false
at first time and generated code will be return.
You can use Promise
and async
function to solve your problem
const FIND_EXISITNG_COURT =
"SELECT access_code,team1,team2 FROM courts WHERE access_code= ?";
function selectByCode(code) {
return new Promise((resolve, reject) => {
connection.query(FIND_EXISITNG_COURT, [code], (err, results) => {
if (err) {
reject(err);
} else {
resolve(results.length)
}
});
}
async function generateAccessCode() {
var random = Math.floor(Math.random() * (+30 - +0)) + +0;
var code = random.toString(16);
var hasDupe = false;
let count =0;
try{
do {
count = await selectByCode(code);
if (count > 0) {
random = Math.floor(Math.random() * (+30 - +0)) + +0;
code = random.toString(16);
hasDupe = true;
} else {
hasDupe = false;
}
} while (hasDupe);
return code;
}
catch(e){
throw e;
}
}
answered Nov 20 '18 at 5:57
Milad AghamohammadiMilad Aghamohammadi
841515
841515
This works great! Thank you so much :)
– Auralieas
Nov 20 '18 at 6:17
add a comment |
This works great! Thank you so much :)
– Auralieas
Nov 20 '18 at 6:17
This works great! Thank you so much :)
– Auralieas
Nov 20 '18 at 6:17
This works great! Thank you so much :)
– Auralieas
Nov 20 '18 at 6:17
add a comment |
Your call to connection.query
is asynchronous, meaning the callback you've defined does not run right away. Your code just registers that callback and then keeps on executing until the end of generateAccessCode
. The callback doesn't get called until much later (when the db returns something) so hasDupe
gets set only long after the original function has already exited.
You basically have 3 options to handle this: callbacks, promises, or async/await (which is really just syntactic sugar on top of promises).
An example using async/await but trying to keep as close to your original structure as I can (run it more than once to see it working):
// this is a mock for the db call. This "database" already holds records with IDs 0, 2 and 3.
// IRL you will need to wrap your db call in a function that returns a promise
// if you want to do it this way
const connectionQuery = function (code) {
return new Promise((resolve) => {
setTimeout(() => resolve(code === 1 ? : [true]), 1000);
});
}
async function generateAccessCode() {
// simplified the code generation for this example
let code = Math.floor(Math.random() * 4); // Code can be 0, 1, 2, or 3
let hasDupe = false;
let results;
do {
results = await connectionQuery(code); // await here is the key
if (results.length > 0) {
console.log(`Code ${code} already exists in the database. Generating new code...`);
code = Math.floor(Math.random() * 4);
hasDupe = true;
} else {
hasDupe = false;
}
} while (hasDupe);
return code;
}
generateAccessCode()
.then((code) => {
console.log(`Final result: ${code}`);
})
.catch((err) => {
console.log(err);
});
Using callbacks instead:
// this is a mock for the db call. This "database" already holds records with IDs 0, 2 and 3.
const connectionQuery = function (code, callback) {
setTimeout(() => {
callback(null, code === 1 ? : [true]);
}, 1000);
}
function generateAccessCode(callback) {
// simplified the code generation for this example
let code = Math.floor(Math.random() * 4); // Code can be 0, 1, 2, or 3
let hasDupe = false;
let results;
connectionQuery(code, (err, results) => {
if (err) {
return callback(err);
}
if (results.length) {
console.log(`Code ${code} already exists in the DB`);
return generateAccessCode(callback);
}
callback(null, code);
});
}
generateAccessCode((err, code) => {
console.log(`Final result: ${code}`);
});
Thank you for all the code examples! Definitely learned more about asynchronous functions and how to handle them.
– Auralieas
Nov 20 '18 at 6:18
add a comment |
Your call to connection.query
is asynchronous, meaning the callback you've defined does not run right away. Your code just registers that callback and then keeps on executing until the end of generateAccessCode
. The callback doesn't get called until much later (when the db returns something) so hasDupe
gets set only long after the original function has already exited.
You basically have 3 options to handle this: callbacks, promises, or async/await (which is really just syntactic sugar on top of promises).
An example using async/await but trying to keep as close to your original structure as I can (run it more than once to see it working):
// this is a mock for the db call. This "database" already holds records with IDs 0, 2 and 3.
// IRL you will need to wrap your db call in a function that returns a promise
// if you want to do it this way
const connectionQuery = function (code) {
return new Promise((resolve) => {
setTimeout(() => resolve(code === 1 ? : [true]), 1000);
});
}
async function generateAccessCode() {
// simplified the code generation for this example
let code = Math.floor(Math.random() * 4); // Code can be 0, 1, 2, or 3
let hasDupe = false;
let results;
do {
results = await connectionQuery(code); // await here is the key
if (results.length > 0) {
console.log(`Code ${code} already exists in the database. Generating new code...`);
code = Math.floor(Math.random() * 4);
hasDupe = true;
} else {
hasDupe = false;
}
} while (hasDupe);
return code;
}
generateAccessCode()
.then((code) => {
console.log(`Final result: ${code}`);
})
.catch((err) => {
console.log(err);
});
Using callbacks instead:
// this is a mock for the db call. This "database" already holds records with IDs 0, 2 and 3.
const connectionQuery = function (code, callback) {
setTimeout(() => {
callback(null, code === 1 ? : [true]);
}, 1000);
}
function generateAccessCode(callback) {
// simplified the code generation for this example
let code = Math.floor(Math.random() * 4); // Code can be 0, 1, 2, or 3
let hasDupe = false;
let results;
connectionQuery(code, (err, results) => {
if (err) {
return callback(err);
}
if (results.length) {
console.log(`Code ${code} already exists in the DB`);
return generateAccessCode(callback);
}
callback(null, code);
});
}
generateAccessCode((err, code) => {
console.log(`Final result: ${code}`);
});
Thank you for all the code examples! Definitely learned more about asynchronous functions and how to handle them.
– Auralieas
Nov 20 '18 at 6:18
add a comment |
Your call to connection.query
is asynchronous, meaning the callback you've defined does not run right away. Your code just registers that callback and then keeps on executing until the end of generateAccessCode
. The callback doesn't get called until much later (when the db returns something) so hasDupe
gets set only long after the original function has already exited.
You basically have 3 options to handle this: callbacks, promises, or async/await (which is really just syntactic sugar on top of promises).
An example using async/await but trying to keep as close to your original structure as I can (run it more than once to see it working):
// this is a mock for the db call. This "database" already holds records with IDs 0, 2 and 3.
// IRL you will need to wrap your db call in a function that returns a promise
// if you want to do it this way
const connectionQuery = function (code) {
return new Promise((resolve) => {
setTimeout(() => resolve(code === 1 ? : [true]), 1000);
});
}
async function generateAccessCode() {
// simplified the code generation for this example
let code = Math.floor(Math.random() * 4); // Code can be 0, 1, 2, or 3
let hasDupe = false;
let results;
do {
results = await connectionQuery(code); // await here is the key
if (results.length > 0) {
console.log(`Code ${code} already exists in the database. Generating new code...`);
code = Math.floor(Math.random() * 4);
hasDupe = true;
} else {
hasDupe = false;
}
} while (hasDupe);
return code;
}
generateAccessCode()
.then((code) => {
console.log(`Final result: ${code}`);
})
.catch((err) => {
console.log(err);
});
Using callbacks instead:
// this is a mock for the db call. This "database" already holds records with IDs 0, 2 and 3.
const connectionQuery = function (code, callback) {
setTimeout(() => {
callback(null, code === 1 ? : [true]);
}, 1000);
}
function generateAccessCode(callback) {
// simplified the code generation for this example
let code = Math.floor(Math.random() * 4); // Code can be 0, 1, 2, or 3
let hasDupe = false;
let results;
connectionQuery(code, (err, results) => {
if (err) {
return callback(err);
}
if (results.length) {
console.log(`Code ${code} already exists in the DB`);
return generateAccessCode(callback);
}
callback(null, code);
});
}
generateAccessCode((err, code) => {
console.log(`Final result: ${code}`);
});
Your call to connection.query
is asynchronous, meaning the callback you've defined does not run right away. Your code just registers that callback and then keeps on executing until the end of generateAccessCode
. The callback doesn't get called until much later (when the db returns something) so hasDupe
gets set only long after the original function has already exited.
You basically have 3 options to handle this: callbacks, promises, or async/await (which is really just syntactic sugar on top of promises).
An example using async/await but trying to keep as close to your original structure as I can (run it more than once to see it working):
// this is a mock for the db call. This "database" already holds records with IDs 0, 2 and 3.
// IRL you will need to wrap your db call in a function that returns a promise
// if you want to do it this way
const connectionQuery = function (code) {
return new Promise((resolve) => {
setTimeout(() => resolve(code === 1 ? : [true]), 1000);
});
}
async function generateAccessCode() {
// simplified the code generation for this example
let code = Math.floor(Math.random() * 4); // Code can be 0, 1, 2, or 3
let hasDupe = false;
let results;
do {
results = await connectionQuery(code); // await here is the key
if (results.length > 0) {
console.log(`Code ${code} already exists in the database. Generating new code...`);
code = Math.floor(Math.random() * 4);
hasDupe = true;
} else {
hasDupe = false;
}
} while (hasDupe);
return code;
}
generateAccessCode()
.then((code) => {
console.log(`Final result: ${code}`);
})
.catch((err) => {
console.log(err);
});
Using callbacks instead:
// this is a mock for the db call. This "database" already holds records with IDs 0, 2 and 3.
const connectionQuery = function (code, callback) {
setTimeout(() => {
callback(null, code === 1 ? : [true]);
}, 1000);
}
function generateAccessCode(callback) {
// simplified the code generation for this example
let code = Math.floor(Math.random() * 4); // Code can be 0, 1, 2, or 3
let hasDupe = false;
let results;
connectionQuery(code, (err, results) => {
if (err) {
return callback(err);
}
if (results.length) {
console.log(`Code ${code} already exists in the DB`);
return generateAccessCode(callback);
}
callback(null, code);
});
}
generateAccessCode((err, code) => {
console.log(`Final result: ${code}`);
});
// this is a mock for the db call. This "database" already holds records with IDs 0, 2 and 3.
// IRL you will need to wrap your db call in a function that returns a promise
// if you want to do it this way
const connectionQuery = function (code) {
return new Promise((resolve) => {
setTimeout(() => resolve(code === 1 ? : [true]), 1000);
});
}
async function generateAccessCode() {
// simplified the code generation for this example
let code = Math.floor(Math.random() * 4); // Code can be 0, 1, 2, or 3
let hasDupe = false;
let results;
do {
results = await connectionQuery(code); // await here is the key
if (results.length > 0) {
console.log(`Code ${code} already exists in the database. Generating new code...`);
code = Math.floor(Math.random() * 4);
hasDupe = true;
} else {
hasDupe = false;
}
} while (hasDupe);
return code;
}
generateAccessCode()
.then((code) => {
console.log(`Final result: ${code}`);
})
.catch((err) => {
console.log(err);
});
// this is a mock for the db call. This "database" already holds records with IDs 0, 2 and 3.
// IRL you will need to wrap your db call in a function that returns a promise
// if you want to do it this way
const connectionQuery = function (code) {
return new Promise((resolve) => {
setTimeout(() => resolve(code === 1 ? : [true]), 1000);
});
}
async function generateAccessCode() {
// simplified the code generation for this example
let code = Math.floor(Math.random() * 4); // Code can be 0, 1, 2, or 3
let hasDupe = false;
let results;
do {
results = await connectionQuery(code); // await here is the key
if (results.length > 0) {
console.log(`Code ${code} already exists in the database. Generating new code...`);
code = Math.floor(Math.random() * 4);
hasDupe = true;
} else {
hasDupe = false;
}
} while (hasDupe);
return code;
}
generateAccessCode()
.then((code) => {
console.log(`Final result: ${code}`);
})
.catch((err) => {
console.log(err);
});
// this is a mock for the db call. This "database" already holds records with IDs 0, 2 and 3.
const connectionQuery = function (code, callback) {
setTimeout(() => {
callback(null, code === 1 ? : [true]);
}, 1000);
}
function generateAccessCode(callback) {
// simplified the code generation for this example
let code = Math.floor(Math.random() * 4); // Code can be 0, 1, 2, or 3
let hasDupe = false;
let results;
connectionQuery(code, (err, results) => {
if (err) {
return callback(err);
}
if (results.length) {
console.log(`Code ${code} already exists in the DB`);
return generateAccessCode(callback);
}
callback(null, code);
});
}
generateAccessCode((err, code) => {
console.log(`Final result: ${code}`);
});
// this is a mock for the db call. This "database" already holds records with IDs 0, 2 and 3.
const connectionQuery = function (code, callback) {
setTimeout(() => {
callback(null, code === 1 ? : [true]);
}, 1000);
}
function generateAccessCode(callback) {
// simplified the code generation for this example
let code = Math.floor(Math.random() * 4); // Code can be 0, 1, 2, or 3
let hasDupe = false;
let results;
connectionQuery(code, (err, results) => {
if (err) {
return callback(err);
}
if (results.length) {
console.log(`Code ${code} already exists in the DB`);
return generateAccessCode(callback);
}
callback(null, code);
});
}
generateAccessCode((err, code) => {
console.log(`Final result: ${code}`);
});
answered Nov 20 '18 at 6:07
PysulPysul
384514
384514
Thank you for all the code examples! Definitely learned more about asynchronous functions and how to handle them.
– Auralieas
Nov 20 '18 at 6:18
add a comment |
Thank you for all the code examples! Definitely learned more about asynchronous functions and how to handle them.
– Auralieas
Nov 20 '18 at 6:18
Thank you for all the code examples! Definitely learned more about asynchronous functions and how to handle them.
– Auralieas
Nov 20 '18 at 6:18
Thank you for all the code examples! Definitely learned more about asynchronous functions and how to handle them.
– Auralieas
Nov 20 '18 at 6:18
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53386621%2fnodejs-mysql-query-in-loop-returning-before-intented%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
You have a sync problem. Your loop will run and not wait for the inner-function call to return. The most easy solution is to make the loop recursive inside the connection.query function
– split
Nov 20 '18 at 5:30