3

I am trying to make this code return each employees name.

var company = {
    employees: [
        {
            name: "doug"
        },
        {
            name: "AJ"
        }
    ],
    getName: function(employee){
        return employee.name
    },
    getNames: function(){
        return this.employees.map(this.getName)
    },
    delayedGetNames: function(){
        setTimeout(this.getNames,500)
    }
}

console.log(company.delayedGetNames());

However, when I run the code I get "TypeError: Cannot read property 'map' of undefined"

I have tried doing

setTimeout(this.getNames.bind(this),500)

I just get undefined returned to me.

Can anyone help me out?

brff19
  • 760
  • 1
  • 8
  • 21
  • 3
    `setTimeout` has no return value. Your `console.log` will always return undefined. You need to use Promises. – lolbas Feb 28 '18 at 08:47
  • 1
    Possible duplicate of [Get return value from setTimeout](https://stackoverflow.com/questions/24928846/get-return-value-from-settimeout) – lolbas Feb 28 '18 at 08:47

3 Answers3

3

You need to add a callback to your function in order to get the names.

var company = {
    employees: [
        {
            name: "doug"
        },
        {
            name: "AJ"
        }
    ],
    getName: function(employee){
        return employee.name
    },
    getNames: function(){
        return this.employees.map(this.getName)
    },
    delayedGetNames: function(cb){
        setTimeout(()=>cb(this.getNames()),500)
    }
}
company.delayedGetNames(names => console.log(names))
Giannis Mp
  • 1,291
  • 6
  • 13
1

Or, using Promise, you could write something like this:

var company = {
    employees: [
        {
            name: "doug"
        },
        {
            name: "AJ"
        }
    ],
    getName: function(employee){
        return employee.name
    },
    getNames: function(){
        return this.employees.map(this.getName)
    },
    delayedGetNames: function() {
        return new Promise(resolve => setTimeout(() => resolve(this.getNames()), 1000));
    }
}

company.delayedGetNames().then(console.log);
Kirill Simonov
  • 8,257
  • 3
  • 18
  • 42
1

With few tricks and getters

var company = {
    employees: [
        {
            name: "doug"
        },
        {
            name: "AJ"
        }
    ],
    getName: function(employee){
        return employee.name
    },
    get getNames(){
        console.log(this.employees.map(x => this.getName(x)));
    },
    get delayedGetNames(){
        setTimeout(this.getNames,500)
    }
}

console.log(company.delayedGetNames);
izengod
  • 1,116
  • 5
  • 17
  • 41