我有一个异步函数,我发送给另一个异步函数,等待该诺言的解决,但由于某种原因,它不等待重新处理。
Router.get("/openPage/:id",async(res,req)=>{
var parms = res.getHeaderParamas();
let select = OpenTemplate(parms);
let theResualt = await select.then(data=>data);
connection.end();
res.returnJson(theResualt,"Success");
});
async function OpenTemplate(header){
return new Promise(res=>{
var query = `SELECT * FROM streamingpages WHERE ID=${header.routerParamas.id}`;
connection.connect((err)=>{res(err)});
connection.query(query,(error, results, fields)=>{
if(error) res(error)
console.log(results);
res(results);
});
})
}
我不明白我在做什么错??
答案 0 :(得分:0)
在这一行:
connection.connect((err)=>{res(err)});
您可以在建立连接时而不是在查询完成时解决承诺。您不能多次解决Promise。
function makeQuery(connection, query) {
return new Promise((resolve, reject) => {
connection.connect(error => {
if(error) return reject(error);
connection.query(query, (error, results, fields) => {
if(error) return reject(error);
console.log(results);
resolve(results);
connection.close(); // actually you should open the connection to the db once ...
});
});
});
}
const openTemplate = header =>
makeQuery(connection, `SELECT * FROM streamingpages WHERE ID=${header.routerParamas.id}`); // MYSQL INJECTION POSSIBLE!!!!
Router.get("/openPage/:id",async(res,req)=>{
var params = res.getHeaderParams();
const result = await openTemplate(parms);
res.returnJson(result, "Success");
});