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?

2
  • 3
    setTimeout has no return value. Your console.log will always return undefined. You need to use Promises. Commented Feb 28, 2018 at 8:47
  • 1
    Possible duplicate of Get return value from setTimeout Commented Feb 28, 2018 at 8:47

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.