我正在使用express js开发api,在我的api调用中,我调用了2个函数,首先是login()
,而其他函数是get_organizations()
,但是调用get_organization()
却没有完成{{ 1}}函数,我已经使用了async await,但是它不能正常工作,任何人都可以帮助我解决此问题吗?我在这里添加了整个代码,
login()
答案 0 :(得分:2)
调用函数时使用await
时,基本上是在等待该函数中的Promise解析。调用的函数旨在返回该诺言。
在您的代码中,login
函数确实调用了connection.query
,但是没有任何等待查询解决的保证。
为了使await
真正地等待connection.query
,您需要返回一个Promise,该Promise会在用户最终登录时解决-即您拥有令牌:
const login = async function () {
try {
console.log('Login process started');
const newToken = await jwt.sign({login:'login'},config['token-secret'],{ expiresIn: config['token-expires']});
let username = 'root_admin'
let password = 'Admin123';
let token = String(cryptojs.lib.WordArray.random(20));
console.log("token : "+token);
return new Promise(function(resolve, reject){
connection.query('SELECT * FROM users where username = ? ',[username], async function(err, rows) { // await won't do anything here,
// you should only use await with functions that return promises.
if (err) {
console.log("Looged out failed");
throw new Error(err);
} else {
const user = rows[0];
console.log("psdsdsd");
if(bcrypt.compareSync(password,user.passwordHash)) {
await connection.query('SELECT * FROM organizations where id = ? ',[user.organizationId], async function(err, org_data) {
if (err) {
console.log("Looged out failed");
throw new Error(err);
} else {
console.log("sdsd");
//console.log(org_data);
if(typeof org_data.name!='undefined') {
organization = org_data.name;
} else {
organization = 'VeriCurious';
}
//console.log(organization);
// create a token
const token = await jwt.sign({ id: user.id, username: user.username, organizationId: user.organizationId, organization: organization}, config['token-secret'], {
expiresIn: config['token-expires'] // expires in 30 minutes
});
console.log("Successfull loggedin");
console.log("New generated token : "+token);
resolve(token); // this signals the Promise to resolve.
// return token;
}
});
}
}
});
});
} catch (error) {
console.log(error);
}
}
一些注意事项:
connection.query
进行了回调,因此await
在那里没有用。例如,如果connection.query
返回了Promise,则可以执行以下操作:
const login = async function () {
// skipped a lot of code and logic since this is an example
const rows = await connection.query('SELECT * FROM users where username = ? ',[username]);
const user = rows[0];
const org_data = await connection.query('SELECT * FROM organizations where id = ? ',[user.organizationId]);
const organization = org_data.name;
return await jwt.sign({ id: user.id, username: user.username, organizationId: user.organizationId, organization: organization}, config['token-secret'], {
expiresIn: config['token-expires'] // expires in 30 minutes
});
}
处理错误真的很简单。
async
函数内部进行了回调,并且您将返回一个新的Promise(例如在我的示例中),我真的不知道对于reject
还是更好throw
错误。我认为两者都会做同样的事情,但我不确定。