Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function call on object with delay

Tags:

javascript

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?

like image 742
brff19 Avatar asked May 20 '26 07:05

brff19


2 Answers

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))
like image 125
Giannis Mp Avatar answered May 23 '26 19:05

Giannis Mp


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);
like image 43
Kirill Simonov Avatar answered May 23 '26 21:05

Kirill Simonov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!