我在節點js中制作api,在一個api中我將一些資料呼叫到一個api中。問題是這很慢,有什么方法可以提高效率嗎?
constructor() {
this.userExperienceRepository = new UserExperienceRepository();
this.userEducationRepository = new UserEducationRepository();
this.userCertificationRepository = new UserCertificationRepository();
this.userExpertiseRepository = new UserExpertiseRepository();
this.userEquipmentRepository = new UserEquipmentRepository();
this.userRepository = new UserRepository();
}
async findAllByUserId(id) {
let profileDetail={};
profileDetail.user = await this.userRepository.findAllById(id);
profileDetail.user= deleteSecurityProperties(profileDetail.user);
profileDetail.experience = await this.userExperienceRepository.findAllByUserId(id);
profileDetail.education = await this.userEducationRepository.findAllByUserId(id);
profileDetail.certification = await this.userCertificationRepository.findAllByUserId(id);
profileDetail.expertise = await this.userExpertiseRepository.findAllByUserId(id);
profileDetail.equipment = await this.userEquipmentRepository.findAllByUserId(id);
return profileDetail;
}
}
function deleteSecurityProperties(user) {
delete user.password;
delete user.otp;
delete user.otpAttempts;
delete user.otpTimestamp;
return user;
}
uj5u.com熱心網友回復:
您正在執行一系列似乎并不相互依賴的異步呼叫,因此如果您并行執行它們,您可能會看到輕微的改進:
async findAllByUserId(id) {
let profileDetail = {};
profileDetail.user = await this.userRepository.findAllById(id);
profileDetail.user = deleteSecurityProperties(profileDetail.user);
[
profileDetail.experience,
profileDetail.education,
profileDetail.certification,
profileDetail.expertise,
profileDetail.equipment,
] = await Promise.all([
this.userExperienceRepository.findAllByUserId(id),
this.userEducationRepository.findAllByUserId(id),
this.userCertificationRepository.findAllByUserId(id),
this.userExpertiseRepository.findAllByUserId(id),
this.userEquipmentRepository.findAllByUserId(id),
]);
return profileDetail;
}
(Promise.all實作其承諾的陣列保證按照它作為輸入接收的可迭代 [在這種情況下為陣列] 的順序。)
您可能可以在其中包含profileDetail.user分配,但我不清楚那里發生了什么,因為您分配了兩次。盡管如此,我認為這做同樣的事情(假設何時deleteSecurityProperties被呼叫相對于findAllByUserId它后面的呼叫并不重要):
async findAllByUserId(id) {
let profileDetail = {};
[
profileDetail.user,
profileDetail.experience,
profileDetail.education,
profileDetail.certification,
profileDetail.expertise,
profileDetail.equipment,
] = await Promise.all([
this.userRepository.findAllById(id)).then(deleteSecurityProperties),
this.userExperienceRepository.findAllByUserId(id),
this.userEducationRepository.findAllByUserId(id),
this.userCertificationRepository.findAllByUserId(id),
this.userExpertiseRepository.findAllByUserId(id),
this.userEquipmentRepository.findAllByUserId(id),
]);
return profileDetail;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/430789.html
標籤:javascript 节点.js
