js
I just create a 2 function to send the response var = y but unfortunately res.end() work before then my y++ works..
This code work well with for loop without mine query
but when i used a query it working stop and it gives res like below.
Before promise call.
Loop completed.
Promise resolved: 0
Next step.
13289
2170
2165
2146
2115
2138
2143
2112
1964
2685
6945
2687
2688
2902
2935
2941
3094
3095
3164
3096
//1. Create a new function that returns a promise
function firstFunction() {
return new Promise((resolve, reject) => {
let y = 0
con.connect(function (err) {
if (err) throw err;
con.query("SELECT * FROM wp_posts WHERE `post_type` = 'post'", async function (err, result, fields) {
if (err) throw err;
result.forEach(element => {
console.log(element['ID']);
y++;
});
// get the results from post table
});
});
// for (i = 0; i < 100; i++) {
// y++
// }
console.log('Loop completed.')
resolve(y)
})
}
//2. Create an async function
async function secondFunction() {
console.log('Before promise call.')
//3. Await for the first function to complete
const result = await firstFunction()
console.log('Promise resolved: ' + result)
console.log('Next step.')
res.end();
};
secondFunction()
>Solution :
How about this…
//1. Create a new function that returns a promise
function firstFunction() {
return new Promise((resolve, reject) => {
let y = 0
con.connect(function (err) {
if (err) throw err;
con.query("SELECT * FROM wp_posts WHERE `post_type` = 'post'", async function (err, result, fields) {
if (err) throw err;
result.forEach(element => {
console.log(element['ID']);
y++;
});
// get the results from post table
console.log('Loop completed.')
resolve(y); // <---- Resolve the promise here
});
});
// for (i = 0; i < 100; i++) {
// y++
// }
// console.log('Loop completed.')
// resolve(y) // <--- Moving this inside con.query callback
})
}
//2. Create an async function
async function secondFunction() {
console.log('Before promise call.')
//3. Await for the first function to complete
const result = await firstFunction()
console.log('Promise resolved: ' + result)
console.log('Next step.')
res.end();
};
secondFunction()