How can I execute an mySQL query in another MySQL query with express.js
we have an issue when we want to execute a query that takes the output from another query.
connection.query(`SELECT * from Database.table1`, function (err, rows, fields) {
for (var item of rows) {
allcounts += item.count
number = item.number
console.log(allcounts)
console.log(number)
connection.query(`DELETE from Database.table2 where numbers = ${number}`, function (err, rows, fields) {
console.log("delete successfull")
})
console.log("Step One finished !")
}
})
The way it should work is, that rows in the first query is returning two JSON objects. Each object stands for a specific product with a count(count) and a product number(number). This products should be deleted in another table in the database.
You can see that we want to loop through the output(rows) of our first statement and execute another statement with this output(rows). This works but express is executing the code in the wrong direction...
Heres the output:
0.89
12345
Step One finished!
2.28
32598
Step One finished!
delete successfull
delete successfull
Its showing us the number and is adding the counts correctly!
The strange thing is that both queries are executed AFTER both counts are added and the number is shown...
We tried several solutions but no one was the right for us.
It would be great if anyone could help us soon :)
javascript mysql express
add a comment |
we have an issue when we want to execute a query that takes the output from another query.
connection.query(`SELECT * from Database.table1`, function (err, rows, fields) {
for (var item of rows) {
allcounts += item.count
number = item.number
console.log(allcounts)
console.log(number)
connection.query(`DELETE from Database.table2 where numbers = ${number}`, function (err, rows, fields) {
console.log("delete successfull")
})
console.log("Step One finished !")
}
})
The way it should work is, that rows in the first query is returning two JSON objects. Each object stands for a specific product with a count(count) and a product number(number). This products should be deleted in another table in the database.
You can see that we want to loop through the output(rows) of our first statement and execute another statement with this output(rows). This works but express is executing the code in the wrong direction...
Heres the output:
0.89
12345
Step One finished!
2.28
32598
Step One finished!
delete successfull
delete successfull
Its showing us the number and is adding the counts correctly!
The strange thing is that both queries are executed AFTER both counts are added and the number is shown...
We tried several solutions but no one was the right for us.
It would be great if anyone could help us soon :)
javascript mysql express
Thosedelete successful
messages only get printed later, becauseconnection.query
runs asynchronously. The execution does not wait until it is finished and immediately printsStep One finished !
.
– chrisg86
Jan 2 at 18:03
Thanks but the delete query isn't working as well...
– unexpected_code_at_line_1
Jan 2 at 18:05
Try logging the error, the second query might have failed. Otherwise you can console log the raw sql query and run it directly on the database server to see if that works.
– chrisg86
Jan 2 at 18:07
The query is correct, we ran it directly on the server.
– unexpected_code_at_line_1
Jan 2 at 19:42
Try loggingerr
in the callback of the delete query. You usually should check if this is something else thannull
orundefined
.
– chrisg86
Jan 2 at 20:37
add a comment |
we have an issue when we want to execute a query that takes the output from another query.
connection.query(`SELECT * from Database.table1`, function (err, rows, fields) {
for (var item of rows) {
allcounts += item.count
number = item.number
console.log(allcounts)
console.log(number)
connection.query(`DELETE from Database.table2 where numbers = ${number}`, function (err, rows, fields) {
console.log("delete successfull")
})
console.log("Step One finished !")
}
})
The way it should work is, that rows in the first query is returning two JSON objects. Each object stands for a specific product with a count(count) and a product number(number). This products should be deleted in another table in the database.
You can see that we want to loop through the output(rows) of our first statement and execute another statement with this output(rows). This works but express is executing the code in the wrong direction...
Heres the output:
0.89
12345
Step One finished!
2.28
32598
Step One finished!
delete successfull
delete successfull
Its showing us the number and is adding the counts correctly!
The strange thing is that both queries are executed AFTER both counts are added and the number is shown...
We tried several solutions but no one was the right for us.
It would be great if anyone could help us soon :)
javascript mysql express
we have an issue when we want to execute a query that takes the output from another query.
connection.query(`SELECT * from Database.table1`, function (err, rows, fields) {
for (var item of rows) {
allcounts += item.count
number = item.number
console.log(allcounts)
console.log(number)
connection.query(`DELETE from Database.table2 where numbers = ${number}`, function (err, rows, fields) {
console.log("delete successfull")
})
console.log("Step One finished !")
}
})
The way it should work is, that rows in the first query is returning two JSON objects. Each object stands for a specific product with a count(count) and a product number(number). This products should be deleted in another table in the database.
You can see that we want to loop through the output(rows) of our first statement and execute another statement with this output(rows). This works but express is executing the code in the wrong direction...
Heres the output:
0.89
12345
Step One finished!
2.28
32598
Step One finished!
delete successfull
delete successfull
Its showing us the number and is adding the counts correctly!
The strange thing is that both queries are executed AFTER both counts are added and the number is shown...
We tried several solutions but no one was the right for us.
It would be great if anyone could help us soon :)
connection.query(`SELECT * from Database.table1`, function (err, rows, fields) {
for (var item of rows) {
allcounts += item.count
number = item.number
console.log(allcounts)
console.log(number)
connection.query(`DELETE from Database.table2 where numbers = ${number}`, function (err, rows, fields) {
console.log("delete successfull")
})
console.log("Step One finished !")
}
})
connection.query(`SELECT * from Database.table1`, function (err, rows, fields) {
for (var item of rows) {
allcounts += item.count
number = item.number
console.log(allcounts)
console.log(number)
connection.query(`DELETE from Database.table2 where numbers = ${number}`, function (err, rows, fields) {
console.log("delete successfull")
})
console.log("Step One finished !")
}
})
0.89
12345
Step One finished!
2.28
32598
Step One finished!
delete successfull
delete successfull
0.89
12345
Step One finished!
2.28
32598
Step One finished!
delete successfull
delete successfull
javascript mysql express
javascript mysql express
asked Jan 2 at 17:56
unexpected_code_at_line_1unexpected_code_at_line_1
11
11
Thosedelete successful
messages only get printed later, becauseconnection.query
runs asynchronously. The execution does not wait until it is finished and immediately printsStep One finished !
.
– chrisg86
Jan 2 at 18:03
Thanks but the delete query isn't working as well...
– unexpected_code_at_line_1
Jan 2 at 18:05
Try logging the error, the second query might have failed. Otherwise you can console log the raw sql query and run it directly on the database server to see if that works.
– chrisg86
Jan 2 at 18:07
The query is correct, we ran it directly on the server.
– unexpected_code_at_line_1
Jan 2 at 19:42
Try loggingerr
in the callback of the delete query. You usually should check if this is something else thannull
orundefined
.
– chrisg86
Jan 2 at 20:37
add a comment |
Thosedelete successful
messages only get printed later, becauseconnection.query
runs asynchronously. The execution does not wait until it is finished and immediately printsStep One finished !
.
– chrisg86
Jan 2 at 18:03
Thanks but the delete query isn't working as well...
– unexpected_code_at_line_1
Jan 2 at 18:05
Try logging the error, the second query might have failed. Otherwise you can console log the raw sql query and run it directly on the database server to see if that works.
– chrisg86
Jan 2 at 18:07
The query is correct, we ran it directly on the server.
– unexpected_code_at_line_1
Jan 2 at 19:42
Try loggingerr
in the callback of the delete query. You usually should check if this is something else thannull
orundefined
.
– chrisg86
Jan 2 at 20:37
Those
delete successful
messages only get printed later, because connection.query
runs asynchronously. The execution does not wait until it is finished and immediately prints Step One finished !
.– chrisg86
Jan 2 at 18:03
Those
delete successful
messages only get printed later, because connection.query
runs asynchronously. The execution does not wait until it is finished and immediately prints Step One finished !
.– chrisg86
Jan 2 at 18:03
Thanks but the delete query isn't working as well...
– unexpected_code_at_line_1
Jan 2 at 18:05
Thanks but the delete query isn't working as well...
– unexpected_code_at_line_1
Jan 2 at 18:05
Try logging the error, the second query might have failed. Otherwise you can console log the raw sql query and run it directly on the database server to see if that works.
– chrisg86
Jan 2 at 18:07
Try logging the error, the second query might have failed. Otherwise you can console log the raw sql query and run it directly on the database server to see if that works.
– chrisg86
Jan 2 at 18:07
The query is correct, we ran it directly on the server.
– unexpected_code_at_line_1
Jan 2 at 19:42
The query is correct, we ran it directly on the server.
– unexpected_code_at_line_1
Jan 2 at 19:42
Try logging
err
in the callback of the delete query. You usually should check if this is something else than null
or undefined
.– chrisg86
Jan 2 at 20:37
Try logging
err
in the callback of the delete query. You usually should check if this is something else than null
or undefined
.– chrisg86
Jan 2 at 20:37
add a comment |
2 Answers
2
active
oldest
votes
You can try with 2 solutions other than promises
1) using anonymous function which blocks the for loop for next iteration untill the query is executed
connection.query(`SELECT * from Database.table1`, function (err, rows, fields) {
for (var item of rows) {
(function (item){
allcounts += item.count
number = item.number
console.log(allcounts)
console.log(number)
connection.query(`DELETE from Database.table2 where numbers = ${number}`, function (err, rows, fields) {
console.log("delete successfull")
})
console.log("Step One finished !")
})(item);
}
})
2) using IN in where clause
at takes the output from another query.
connection.query(`SELECT * from Database.table1`, function (err, rows, fields) {
let numbers = ;
for (var item of rows) {
numbers.push(item.number);
}
connection.query(`DELETE from Database.table2 where numbers IN ("+numbers+")`, function (err, rows, fields) {
connection.release();
console.log("delete successfull")
})
console.log("Step One finished !")
})
Thank you, I tried both solutions but it still doesn't work...
– unexpected_code_at_line_1
Jan 2 at 19:40
add a comment |
The problem is that your for-loop doesn't wait for the asynchronous connection.query()
to finish before continuing with the next iteration.
You can use promises to solve that issue.
I've included some commented sample code using promises below
(untested, so you may have to squash a bug) .
Note:
- the second query in the loop doesn't make sense in my opinion.
It's better to do everything in a single query. - Search around and read up on using promises.
You'll be glad you did when you got the basics.
function getNumbers() {
return new Promise(function(resolve, reject) {
connection.query(`SELECT * from Database.table1`,
function(err, rows, fields) {
// if an error occured we let the caller know it didn't work out with reject()
// if everthing went well, we pass on the result data with resolve()
return (err) ? reject(err) : resolve(rows);
});
});
}
getNumbers()
// below code be executed AFTER the first query succesfully completed
.then(function(rows) {
// use Array.prototype.map() with Array.prototype.join()
// to create string of numbers for deletion query,
// while also calculating total
let totalCount = 0;
const numbersTotal = rows
.map(item => {
numbersTotal += item.number;
return item.number;
})
.join();
console.log("String of numbers: " + numbers);
console.log("numbersTotal: " + totalCount);
// now we can achieve the same result
// using only 2 queries instead of a loop
numbers.length > 0 && connection.query(
`DELETE from Database.table2 where numbers in ${numbers}`,
function(err, rows, fields) {
console.log("delete successfull");
}
);
})
.catch(err =>
// stop immediatly when a mysql error occurs
setImmediate(() => {
throw err;
})
);
I am new in javascript and express.js and I have no experience with promises yet. Is there any chance to get an example regarding to my code?
– unexpected_code_at_line_1
Jan 2 at 18:33
Sure, I've updated the answer with some sample code.
– Laurens Deprost
Jan 2 at 22:06
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%2f54010984%2fhow-can-i-execute-an-mysql-query-in-another-mysql-query-with-express-js%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
You can try with 2 solutions other than promises
1) using anonymous function which blocks the for loop for next iteration untill the query is executed
connection.query(`SELECT * from Database.table1`, function (err, rows, fields) {
for (var item of rows) {
(function (item){
allcounts += item.count
number = item.number
console.log(allcounts)
console.log(number)
connection.query(`DELETE from Database.table2 where numbers = ${number}`, function (err, rows, fields) {
console.log("delete successfull")
})
console.log("Step One finished !")
})(item);
}
})
2) using IN in where clause
at takes the output from another query.
connection.query(`SELECT * from Database.table1`, function (err, rows, fields) {
let numbers = ;
for (var item of rows) {
numbers.push(item.number);
}
connection.query(`DELETE from Database.table2 where numbers IN ("+numbers+")`, function (err, rows, fields) {
connection.release();
console.log("delete successfull")
})
console.log("Step One finished !")
})
Thank you, I tried both solutions but it still doesn't work...
– unexpected_code_at_line_1
Jan 2 at 19:40
add a comment |
You can try with 2 solutions other than promises
1) using anonymous function which blocks the for loop for next iteration untill the query is executed
connection.query(`SELECT * from Database.table1`, function (err, rows, fields) {
for (var item of rows) {
(function (item){
allcounts += item.count
number = item.number
console.log(allcounts)
console.log(number)
connection.query(`DELETE from Database.table2 where numbers = ${number}`, function (err, rows, fields) {
console.log("delete successfull")
})
console.log("Step One finished !")
})(item);
}
})
2) using IN in where clause
at takes the output from another query.
connection.query(`SELECT * from Database.table1`, function (err, rows, fields) {
let numbers = ;
for (var item of rows) {
numbers.push(item.number);
}
connection.query(`DELETE from Database.table2 where numbers IN ("+numbers+")`, function (err, rows, fields) {
connection.release();
console.log("delete successfull")
})
console.log("Step One finished !")
})
Thank you, I tried both solutions but it still doesn't work...
– unexpected_code_at_line_1
Jan 2 at 19:40
add a comment |
You can try with 2 solutions other than promises
1) using anonymous function which blocks the for loop for next iteration untill the query is executed
connection.query(`SELECT * from Database.table1`, function (err, rows, fields) {
for (var item of rows) {
(function (item){
allcounts += item.count
number = item.number
console.log(allcounts)
console.log(number)
connection.query(`DELETE from Database.table2 where numbers = ${number}`, function (err, rows, fields) {
console.log("delete successfull")
})
console.log("Step One finished !")
})(item);
}
})
2) using IN in where clause
at takes the output from another query.
connection.query(`SELECT * from Database.table1`, function (err, rows, fields) {
let numbers = ;
for (var item of rows) {
numbers.push(item.number);
}
connection.query(`DELETE from Database.table2 where numbers IN ("+numbers+")`, function (err, rows, fields) {
connection.release();
console.log("delete successfull")
})
console.log("Step One finished !")
})
You can try with 2 solutions other than promises
1) using anonymous function which blocks the for loop for next iteration untill the query is executed
connection.query(`SELECT * from Database.table1`, function (err, rows, fields) {
for (var item of rows) {
(function (item){
allcounts += item.count
number = item.number
console.log(allcounts)
console.log(number)
connection.query(`DELETE from Database.table2 where numbers = ${number}`, function (err, rows, fields) {
console.log("delete successfull")
})
console.log("Step One finished !")
})(item);
}
})
2) using IN in where clause
at takes the output from another query.
connection.query(`SELECT * from Database.table1`, function (err, rows, fields) {
let numbers = ;
for (var item of rows) {
numbers.push(item.number);
}
connection.query(`DELETE from Database.table2 where numbers IN ("+numbers+")`, function (err, rows, fields) {
connection.release();
console.log("delete successfull")
})
console.log("Step One finished !")
})
answered Jan 2 at 19:26
AkKiAkKi
18416
18416
Thank you, I tried both solutions but it still doesn't work...
– unexpected_code_at_line_1
Jan 2 at 19:40
add a comment |
Thank you, I tried both solutions but it still doesn't work...
– unexpected_code_at_line_1
Jan 2 at 19:40
Thank you, I tried both solutions but it still doesn't work...
– unexpected_code_at_line_1
Jan 2 at 19:40
Thank you, I tried both solutions but it still doesn't work...
– unexpected_code_at_line_1
Jan 2 at 19:40
add a comment |
The problem is that your for-loop doesn't wait for the asynchronous connection.query()
to finish before continuing with the next iteration.
You can use promises to solve that issue.
I've included some commented sample code using promises below
(untested, so you may have to squash a bug) .
Note:
- the second query in the loop doesn't make sense in my opinion.
It's better to do everything in a single query. - Search around and read up on using promises.
You'll be glad you did when you got the basics.
function getNumbers() {
return new Promise(function(resolve, reject) {
connection.query(`SELECT * from Database.table1`,
function(err, rows, fields) {
// if an error occured we let the caller know it didn't work out with reject()
// if everthing went well, we pass on the result data with resolve()
return (err) ? reject(err) : resolve(rows);
});
});
}
getNumbers()
// below code be executed AFTER the first query succesfully completed
.then(function(rows) {
// use Array.prototype.map() with Array.prototype.join()
// to create string of numbers for deletion query,
// while also calculating total
let totalCount = 0;
const numbersTotal = rows
.map(item => {
numbersTotal += item.number;
return item.number;
})
.join();
console.log("String of numbers: " + numbers);
console.log("numbersTotal: " + totalCount);
// now we can achieve the same result
// using only 2 queries instead of a loop
numbers.length > 0 && connection.query(
`DELETE from Database.table2 where numbers in ${numbers}`,
function(err, rows, fields) {
console.log("delete successfull");
}
);
})
.catch(err =>
// stop immediatly when a mysql error occurs
setImmediate(() => {
throw err;
})
);
I am new in javascript and express.js and I have no experience with promises yet. Is there any chance to get an example regarding to my code?
– unexpected_code_at_line_1
Jan 2 at 18:33
Sure, I've updated the answer with some sample code.
– Laurens Deprost
Jan 2 at 22:06
add a comment |
The problem is that your for-loop doesn't wait for the asynchronous connection.query()
to finish before continuing with the next iteration.
You can use promises to solve that issue.
I've included some commented sample code using promises below
(untested, so you may have to squash a bug) .
Note:
- the second query in the loop doesn't make sense in my opinion.
It's better to do everything in a single query. - Search around and read up on using promises.
You'll be glad you did when you got the basics.
function getNumbers() {
return new Promise(function(resolve, reject) {
connection.query(`SELECT * from Database.table1`,
function(err, rows, fields) {
// if an error occured we let the caller know it didn't work out with reject()
// if everthing went well, we pass on the result data with resolve()
return (err) ? reject(err) : resolve(rows);
});
});
}
getNumbers()
// below code be executed AFTER the first query succesfully completed
.then(function(rows) {
// use Array.prototype.map() with Array.prototype.join()
// to create string of numbers for deletion query,
// while also calculating total
let totalCount = 0;
const numbersTotal = rows
.map(item => {
numbersTotal += item.number;
return item.number;
})
.join();
console.log("String of numbers: " + numbers);
console.log("numbersTotal: " + totalCount);
// now we can achieve the same result
// using only 2 queries instead of a loop
numbers.length > 0 && connection.query(
`DELETE from Database.table2 where numbers in ${numbers}`,
function(err, rows, fields) {
console.log("delete successfull");
}
);
})
.catch(err =>
// stop immediatly when a mysql error occurs
setImmediate(() => {
throw err;
})
);
I am new in javascript and express.js and I have no experience with promises yet. Is there any chance to get an example regarding to my code?
– unexpected_code_at_line_1
Jan 2 at 18:33
Sure, I've updated the answer with some sample code.
– Laurens Deprost
Jan 2 at 22:06
add a comment |
The problem is that your for-loop doesn't wait for the asynchronous connection.query()
to finish before continuing with the next iteration.
You can use promises to solve that issue.
I've included some commented sample code using promises below
(untested, so you may have to squash a bug) .
Note:
- the second query in the loop doesn't make sense in my opinion.
It's better to do everything in a single query. - Search around and read up on using promises.
You'll be glad you did when you got the basics.
function getNumbers() {
return new Promise(function(resolve, reject) {
connection.query(`SELECT * from Database.table1`,
function(err, rows, fields) {
// if an error occured we let the caller know it didn't work out with reject()
// if everthing went well, we pass on the result data with resolve()
return (err) ? reject(err) : resolve(rows);
});
});
}
getNumbers()
// below code be executed AFTER the first query succesfully completed
.then(function(rows) {
// use Array.prototype.map() with Array.prototype.join()
// to create string of numbers for deletion query,
// while also calculating total
let totalCount = 0;
const numbersTotal = rows
.map(item => {
numbersTotal += item.number;
return item.number;
})
.join();
console.log("String of numbers: " + numbers);
console.log("numbersTotal: " + totalCount);
// now we can achieve the same result
// using only 2 queries instead of a loop
numbers.length > 0 && connection.query(
`DELETE from Database.table2 where numbers in ${numbers}`,
function(err, rows, fields) {
console.log("delete successfull");
}
);
})
.catch(err =>
// stop immediatly when a mysql error occurs
setImmediate(() => {
throw err;
})
);
The problem is that your for-loop doesn't wait for the asynchronous connection.query()
to finish before continuing with the next iteration.
You can use promises to solve that issue.
I've included some commented sample code using promises below
(untested, so you may have to squash a bug) .
Note:
- the second query in the loop doesn't make sense in my opinion.
It's better to do everything in a single query. - Search around and read up on using promises.
You'll be glad you did when you got the basics.
function getNumbers() {
return new Promise(function(resolve, reject) {
connection.query(`SELECT * from Database.table1`,
function(err, rows, fields) {
// if an error occured we let the caller know it didn't work out with reject()
// if everthing went well, we pass on the result data with resolve()
return (err) ? reject(err) : resolve(rows);
});
});
}
getNumbers()
// below code be executed AFTER the first query succesfully completed
.then(function(rows) {
// use Array.prototype.map() with Array.prototype.join()
// to create string of numbers for deletion query,
// while also calculating total
let totalCount = 0;
const numbersTotal = rows
.map(item => {
numbersTotal += item.number;
return item.number;
})
.join();
console.log("String of numbers: " + numbers);
console.log("numbersTotal: " + totalCount);
// now we can achieve the same result
// using only 2 queries instead of a loop
numbers.length > 0 && connection.query(
`DELETE from Database.table2 where numbers in ${numbers}`,
function(err, rows, fields) {
console.log("delete successfull");
}
);
})
.catch(err =>
// stop immediatly when a mysql error occurs
setImmediate(() => {
throw err;
})
);
function getNumbers() {
return new Promise(function(resolve, reject) {
connection.query(`SELECT * from Database.table1`,
function(err, rows, fields) {
// if an error occured we let the caller know it didn't work out with reject()
// if everthing went well, we pass on the result data with resolve()
return (err) ? reject(err) : resolve(rows);
});
});
}
getNumbers()
// below code be executed AFTER the first query succesfully completed
.then(function(rows) {
// use Array.prototype.map() with Array.prototype.join()
// to create string of numbers for deletion query,
// while also calculating total
let totalCount = 0;
const numbersTotal = rows
.map(item => {
numbersTotal += item.number;
return item.number;
})
.join();
console.log("String of numbers: " + numbers);
console.log("numbersTotal: " + totalCount);
// now we can achieve the same result
// using only 2 queries instead of a loop
numbers.length > 0 && connection.query(
`DELETE from Database.table2 where numbers in ${numbers}`,
function(err, rows, fields) {
console.log("delete successfull");
}
);
})
.catch(err =>
// stop immediatly when a mysql error occurs
setImmediate(() => {
throw err;
})
);
function getNumbers() {
return new Promise(function(resolve, reject) {
connection.query(`SELECT * from Database.table1`,
function(err, rows, fields) {
// if an error occured we let the caller know it didn't work out with reject()
// if everthing went well, we pass on the result data with resolve()
return (err) ? reject(err) : resolve(rows);
});
});
}
getNumbers()
// below code be executed AFTER the first query succesfully completed
.then(function(rows) {
// use Array.prototype.map() with Array.prototype.join()
// to create string of numbers for deletion query,
// while also calculating total
let totalCount = 0;
const numbersTotal = rows
.map(item => {
numbersTotal += item.number;
return item.number;
})
.join();
console.log("String of numbers: " + numbers);
console.log("numbersTotal: " + totalCount);
// now we can achieve the same result
// using only 2 queries instead of a loop
numbers.length > 0 && connection.query(
`DELETE from Database.table2 where numbers in ${numbers}`,
function(err, rows, fields) {
console.log("delete successfull");
}
);
})
.catch(err =>
// stop immediatly when a mysql error occurs
setImmediate(() => {
throw err;
})
);
edited Jan 2 at 22:19
answered Jan 2 at 18:06


Laurens DeprostLaurens Deprost
968114
968114
I am new in javascript and express.js and I have no experience with promises yet. Is there any chance to get an example regarding to my code?
– unexpected_code_at_line_1
Jan 2 at 18:33
Sure, I've updated the answer with some sample code.
– Laurens Deprost
Jan 2 at 22:06
add a comment |
I am new in javascript and express.js and I have no experience with promises yet. Is there any chance to get an example regarding to my code?
– unexpected_code_at_line_1
Jan 2 at 18:33
Sure, I've updated the answer with some sample code.
– Laurens Deprost
Jan 2 at 22:06
I am new in javascript and express.js and I have no experience with promises yet. Is there any chance to get an example regarding to my code?
– unexpected_code_at_line_1
Jan 2 at 18:33
I am new in javascript and express.js and I have no experience with promises yet. Is there any chance to get an example regarding to my code?
– unexpected_code_at_line_1
Jan 2 at 18:33
Sure, I've updated the answer with some sample code.
– Laurens Deprost
Jan 2 at 22:06
Sure, I've updated the answer with some sample code.
– Laurens Deprost
Jan 2 at 22:06
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%2f54010984%2fhow-can-i-execute-an-mysql-query-in-another-mysql-query-with-express-js%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
Those
delete successful
messages only get printed later, becauseconnection.query
runs asynchronously. The execution does not wait until it is finished and immediately printsStep One finished !
.– chrisg86
Jan 2 at 18:03
Thanks but the delete query isn't working as well...
– unexpected_code_at_line_1
Jan 2 at 18:05
Try logging the error, the second query might have failed. Otherwise you can console log the raw sql query and run it directly on the database server to see if that works.
– chrisg86
Jan 2 at 18:07
The query is correct, we ran it directly on the server.
– unexpected_code_at_line_1
Jan 2 at 19:42
Try logging
err
in the callback of the delete query. You usually should check if this is something else thannull
orundefined
.– chrisg86
Jan 2 at 20:37