查看参数是否传递及return相关数据
Check if the parameter is passed and return relevant data
我正在尝试编写一个始终 returns 用户数据的方法,而不管参数中传递的学生 ID 是什么。但是如果 studentID 被传递了,我就想获取额外的数据并将其添加到我已经收到的数据中。这是我的代码的样子
async getData(token, studentId) {
let student;
try {
student = await this.getDataWithoutID(token);
} catch(error) {
throw new Error(error);
}
if (studentId) {
//student param for getDataWithID is from the student object above
let studentId = this.getDataWithID(student, studentId);
return studentId;
}
return student;
}
正如您在上面看到的,如果条件为真,我希望同时返回 studenId 对象和学生对象。有一个更好的方法吗? TIA
您可能需要这样的东西:
async getData(token, studentId) {
try {
const student = await this.getDataWithoutID(token);
if (studentId) {
const extraData = await this.getDataWithID(studentId); // Here you fetch the extraData using the studentId
return { ...student, ...extraData }; // Here you "merge" the two objects
}
return student;
} catch (error) {
throw new Error(error);
}
}
您的 try/catch 块应该包含整个功能,而不仅仅是它的一部分。你不应该 return try/catch 块之外的变量。
我正在尝试编写一个始终 returns 用户数据的方法,而不管参数中传递的学生 ID 是什么。但是如果 studentID 被传递了,我就想获取额外的数据并将其添加到我已经收到的数据中。这是我的代码的样子
async getData(token, studentId) {
let student;
try {
student = await this.getDataWithoutID(token);
} catch(error) {
throw new Error(error);
}
if (studentId) {
//student param for getDataWithID is from the student object above
let studentId = this.getDataWithID(student, studentId);
return studentId;
}
return student;
}
正如您在上面看到的,如果条件为真,我希望同时返回 studenId 对象和学生对象。有一个更好的方法吗? TIA
您可能需要这样的东西:
async getData(token, studentId) {
try {
const student = await this.getDataWithoutID(token);
if (studentId) {
const extraData = await this.getDataWithID(studentId); // Here you fetch the extraData using the studentId
return { ...student, ...extraData }; // Here you "merge" the two objects
}
return student;
} catch (error) {
throw new Error(error);
}
}
您的 try/catch 块应该包含整个功能,而不仅仅是它的一部分。你不应该 return try/catch 块之外的变量。