javascript - 检查参数是否传递并返回相关数据
问题描述
我正在尝试编写一个始终返回用户数据的方法,而不管参数中传递的 studentID 是什么。但是,如果通过了 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 块应该包含整个函数,而不仅仅是它的一部分。您不应该在 try/catch 块之外返回变量。
推荐阅读
- python - Flask Python 如何将输入从文本框传递到 POST 请求?
- r - 带有 facet_wrap 的 cowplot::plot_grid - y 轴标题与轴标签重叠
- python - 如何以这种方式平铺张量?(张量流)
- php - TCPDF - 在输出中使用比例数字
- typescript - TypeScript 如何推断回调参数类型
- python - 如何从语音和键盘输入中获得第一个可用结果?
- java - Spring Boot启动应用后直接抛出“java.lang.OutOfMemoryError: unable to create new native thread”
- blazor - Blazor WebAssembly App 无法调用 HTTP PATCH WEB API 方法
- python - 语法错误、无限循环和一堆格式问题
- python - 获取集合 Firestore 中的文档数量