我无法弄清楚为什么继续执行,并且 await 不会暂停执行,直到被调用的函数返回。
在 node.js 应用程序中
联系人.js
async function routes (fastify, options) {
fastify.get('/contact', async (req, reply) => {
let lookup = require('../helpers/validate_school');
let school_info = await lookup.validate(req.hostname.split('.')[0]);
console.log('here: ', school_info);
let school = school_info.school;
...
reply.view('application/application.html', school);
});
};
school.lookup.js
async function validate(hostname){
const con = require('../../config/db').getDb();
let ret = {};
console.log('lets check for school info');
await con.query('SELECT * FROM schools where identifier=? LIMIT ?', [hostname, 1], function(err, res, fields){
if (err) throw err;
if (res.length > 0){
ret.school = JSON.stringify(res[0]);
...
console.log('found: ', ret);
return ret;
} else {
console.log('not found: ', ret);
return ret;
}
});
};
module.exports = {validate: validate};
日志
lets check for school info
here: undefined
found: {
school: '{"id":2,"name":"Second School","school_dbid":"2","primary_color":"purple","secondary_color":"lavender","tertiary_color":"green","quaternary_color":"blue","identifier":"school2","mascot_id":1,"created_at":"2019-11-20T05:22:16.864Z","updated_at":"2019-11-21T17:59:11.956Z"}',
...
}
在继续执行代码块之前,如何确保 lookup.validate 返回?