Closed PedroRuiz closed 6 years ago
It looks like you're treating result
as an array, but you haven't initialized it. Try
var result = [];
But on top of that, result
is not a promise so you can't return
it and use it in the following then()
.
...
var result;
...
result.push(...);
...
return result;
}).then(function (rows) {
...
Thanks @move-zig, I will try it.
Dear @move-zig, I treat to translate my PHP code into TypeScript. It seems I have not enough knowledge of this new language still. You would be so kind show me how?
thanks in advance, sir!
This works for me:
import mysql from 'promise-mysql';
let connection: mysql.Connection;
mysql.createConnection({
host: 'host',
user: 'user',
password: 'password',
database: 'test',
}).then((conn) => {
connection = conn;
return connection.query('select group_id from users_groups where user_id=2');
}).then((rows) => {
const promises = [];
for (let _i = 0; _i < rows.length; _i++) {
const group = rows[_i];
console.log('Resultados parciales antes de query: ' + JSON.stringify(group.group_id), 'select * from groups where id=' + group.group_id);
promises.push(connection.query('select * from groups where id = ?', group.group_id));
}
connection.end();
return Promise.all(promises);
}).then((rows) => {
for (let _i = 0; _i < rows.length; _i++) {
const group = rows[_i];
console.log('resultados parciales de query: ' + JSON.stringify(group));
console.log('Resultados finales: ' + JSON.stringify(group));
}
}).catch((error) => {
if (connection && connection.end) {
connection.end();
}
//logs out the error
console.log(error);
});
Major Changes
.push()
won't failPromse.all(promises)
instead of the simple arrayMinor Changes
'use strict';
(not needed in typescript)var require;
require()
to typescript import
var
to either let
or const
as appropriateresult
to promises
for clarityconnection.query()
parameters to avoid SQL injectionAnd if you want to write in a style you might be more familiar with, consider async
/await
syntax. This is how I would write it:
import mysql from 'promise-mysql';
import Bluebird from 'bluebird';
(async (userId) => {
try {
// create the initial connection
const connection = await mysql.createConnection({
host: 'host',
user: 'user',
password: 'root',
database: 'test'
});
try {
// run the initial query
const userGroupSelectSql = 'SELECT group_id FROM users_groups WHERE user_id = ?';
const userGroups = await connection.query(userGroupSelectSql, userId);
// array for storing our promises
const promises: Bluebird<any>[] = [];
// run the subqueries
const groupSelectSql = 'SELECT * FROM groups WHERE id = ?';
for (const userGroup of userGroups) {
console.log(`Resultados parciales antes de query: select * from groups where id = ${userGroup.group_id}`);
const promise = connection.query(groupSelectSql, userGroup.group_id); // create the promise (not using `await` here)
promises.push(promise); // store the promise in the array
}
// here is where we'll `await` all the promises at once
// note: that instead of an array of database results, we're going to get an array of array of database results
const groupsArray: any[][] = await Promise.all(promises);
for (const groups of groupsArray) { // loop through the array of promise resolutions
for (const group of groups) { // loop through the database results
console.log('Resultados finales: ' + JSON.stringify(group));
}
}
} finally {
// close the connection
connection.end();
}
} catch (error) {
// write errors to the console
console.log(error);
}
})(2);
Also, have you considered using an SQL join instead of running additional queries in a loop?
SELECT g.*
FROM groups g
LEFT JOIN users_groups ug ON ug.group_id = g.id
WHERE ug.user_id = ?
Tone of thanks!!!
Thanks for jumping on this @move-zig!
@PedroRuiz if that's solved the issue, please close it
I have a table of users like that:
gruops table as follows:
and I have too a relation, called users_groups, between users and groups like that:
My intention is collect any group's data of a due user,
but I got:
This javascript comes of
$ bash tsc promise.ts
If your first idea is solve that in a myslq sentence, please forget it: I am trying to chain promises in my real (may be computational?) world.
Thanks in advance!