Search code examples
javascriptnode.jsecmascript-6async-awaites6-promise

Check if the parameter is passed and return relevant data


I am trying to write a method that always returns the user data irrespective of the studentID that is being passed as well in the argument. But if the studentID is passed, I then want to get additional data and add that to the one I am already receiving. Here is what my code looks like

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;
}

As you see above, if the condition is true, I want both the studenId object and student object to be returned. Is there a better way to do this? TIA


Solution

  • Something like this might be what you need:

    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);
        }
    }
    

    Your try/catch block should encompass the whole function not just a part of it. You shouldn't return a variable outside the try/catch block.