对于如下的快速控制器方法,嵌套了几个异步等待,它会有任何性能命中吗?
为简单起见,所有逻辑当前都位于控制器方法中。但我很清楚我可以重构这些。
我在一些承诺解决方案then
上使用了异步。在顶层。我不确定这是否会显着降低性能或是否是一种可论证的做法?
async registerUser(req, res, next) {
const trx = await transaction.start(this.User.knex());
let userData = {};
AuthService.hashPassword(req.body.password)
.then(password => {
userData = {
first_name: req.body.firstName,
last_name: req.body.lastName,
email: req.body.email,
password: password,
tenant_id: req.body.tenantId
};
return userData;
}).then(async userData => {
return this.User
.query()
.insert(userData);
})
.then(async user => {
let token = await AuthService.signPayload(user);
return {
token,
user
};
})
.then(async payload => {
await trx.commit();
console.log(payload);
res.status(201);
res.jsonp({
success: true,
data: {
user: payload.user,
token: payload.token
}
});
}).catch(async e => {
await trx.rollback();
console.log(e);
res.status(400);
res.jsonp({
success: false,
errors: true,
data: {
message: 'Registration failed',
user: userData
}
})
});
}
答案 0 :(得分:2)
我已将您的代码更改为更加同步,因此您可以看到所有优缺点。
关于性能匹配,最好是在代码中使用async/await
的解决方案。
关于这个:
可以重构这些。
const registerUser = (req, res, next) => {
const trx = await transaction.start(this.User.knex());
let password;
try {
password = await AuthService.hashPassword(req.body.password);
} catch (e) {
// Some error. You can throw it or message user or do whatever you want.
console.error("Error with auth", e.message);
return await errorTransaction(res, trx);
}
let userData = {
first_name: req.body.firstName,
last_name: req.body.lastName,
email: req.body.email,
password: password,
tenant_id: req.body.tenantId
};
try {
await this.User.query().insert(userData);
} catch (e) {
console.error("Error during insert", e.message);
return;
}
let token = await AuthService.signPayload(user);
let tokenUserData = {
token,
user
};
try {
await trx.commit();
} catch (e) {
console.error("Error in commit.", e.message);
return await errorTransaction(res, trx, userData);
}
res.status(201);
res.jsonp({
success: true,
data: {
user: payload.user,
token: payload.token
}
});
}
const errorTransaction = async (res, trx, userData={}) => {
await trx.rollback();
res.status(400);
res.jsonp({
success: false,
errors: true,
data: {
message: 'Registration failed',
user: userData
}
});
}