0

So I have 2 JS functions, loadReport is calling getCurrentReport. I've checked that I do have the correct object before returning, and yet the caller does not receive that object. Why?

    getCurrentReport(id) {
        this.reports.forEach(e => {
            if (e.id === id) {
                console.log(e);     // This prints exactly the object that I want
                return e;    // So I assume I should get this object..
            }
        });
    }

    async loadReport(id) {
        var report = this.getCurrentReport(id);
        console.log("Getting:");
        console.log(report);    // And yet I'm getting undefined here?
    },

Someone please explain to me?

Farid
  • 872
  • 1
  • 13
  • 30
  • It depends what `this` is in the context of the call to `loadReport`. Chances are it isn't what you think it is. – phuzi Dec 09 '20 at 10:12
  • "_So I assume I should get this object.._" Incorrect, that `return` just breaks the current `forEach` round. – Teemu Dec 09 '20 at 10:15

2 Answers2

2

getCurrentReport is not returning anything, therefore report will be undefined.

I assume you are using the forEach to try and 'find' the report, if so, you should use Array's find function

getCurrentReport(id) {
   return this.reports.find(e => e.id === id);
}
andy mccullough
  • 9,070
  • 6
  • 32
  • 55
-1

You are returning e inside a forEach . Try declaring a variable outside forEach and assign e to it and return it outside forEach

Refer below

    function getCurrentReport(id) {
      //declare a variable to hold e
        let currentReport;
        //sample arrray taken
        [{id:1,name:"abc"}, {id:2,name:"xyz"}].forEach(e => {
            if (e.id === id) {
                console.log(e);     // This prints exactly the object that I want
                currentReport = e;    // So I assume I should get this object..
            }
        });
        
        //return here
        return currentReport
    }

    async function loadReport(id) {
        var report = getCurrentReport(id);
        console.log("Getting:");
        console.log(report);    // And yet I'm getting undefined here?
    }

    
    setTimeout(() => {
      loadReport(1)
    }, 1000);