首页 > 解决方案 > 检查参数是否传递并返回相关数据

问题描述

我正在尝试编写一个始终返回用户数据的方法,而不管参数中传递的 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

标签: javascriptnode.jsecmascript-6async-awaites6-promise

解决方案


像这样的东西可能是你需要的:

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 块之外返回变量。


推荐阅读