I'm trying to write a query builder similar to the query builder in Laravel but for TypeScript but I have come across a problem with a promise resolving.(我正在尝试编写与Laravel中的查询生成器类似的查询生成器,但是对于TypeScript,但是遇到了Promise解决的问题。)
connection.query(...)
console.log
.then()
import * as mysql from 'mysql'; interface InternalQueryReturnType<T> { results: T; fields?: mysql.FieldInfo[]; } // Cut down version of my builder. export class MySQLBuilder implements IQueryBuilder { protected query<T>(query: string): Promise<InternalQueryReturnType<T>> { return new Promise((resolve, reject) => { const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'dbname', port: 999, }); connection.connect({}, (error) => { reject(error); }); connection.query(query, (error, results, fields) => { if (error) { reject(error); return; } // It is reaching this point. console.log({ results }); // <- This is returning the correct results. resolve({ results, fields }); }); connection.end(); }); } } // My controller. export class PostController { public static index(request: IRequest): Promise<IResponse> { return new Promise((resolve, reject) => { return new Promise((resolve) => { // Testing the raw query which the builder created. new MySQLBuilder().query<any>('SELECT * FROM `users` WHERE `id` = 1 LIMIT 1 OFFSET 0') .then(({ results }) => { // Nothing was passed into this. console.log({ results }); resolve(new JsonResponse(results || {})); }) .catch((error) => { resolve(new JsonResponse(error).status(400)); }); // Builder code. // new MySQLBuilder().table('users') // .where('id', '=', 1) // .first() // .then((value: object | null) => { // console.log(value); // resolve(new JsonResponse(value || {})); // }) // .catch((error) => { // console.error({ error }); // resolve(new JsonResponse(error).status(400)); // }); }); }); } }
connection.connect({}, (error) => { if (error) { reject(error); } });
The solution to this issue was actually this:(这个问题的解决方案实际上是这样的:)
1.4m articles
1.4m replys
5 comments
56.9k users