Tuna Tuna - 11 months ago 53
Javascript Question

Add callback to for loop function

I have a function to which I pass an array or an object, then it looks for specific keys and edits their values accordingly,

function iterate(obj, delta) {
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] == "object") {
} else {
if(property === 'unix_time'){
var bee = parseInt(obj[property]);
var b = bee + parseInt(delta);
obj[property] = b;

Basically, it looks for the "unix_time" key and add a number "delta" to it.

Question: When I call it asynchronous, it becomes undefined, How can I add a callback that I can simply use to determine that the function has finished executing. Or maybe should I add a promise to it?

For example when i run this it returns perfectly

console.log("new one", obj);
iterate(obj, 3600000)

But this is a problem, it becomes undefined

var dd = iterate(obj, 3600000);

Answer Source

As mentioned in comments, you function is synchronous and it returns immediately after you call it like this:

var result = iterate(tree, delta);

However, as it's currently written, the result variable will have value of undefined since your iterate function doesn't return anything.

If you have the setup like this:

var obj = {...};
iterate(obj, 3600000)
console.log(obj) // correctly outputs modified object

It will output modified object, since you're not using here the returned value from the function. However, in this scenario:

console.log("new one", iterate(obj, 3600000)); // ouputs `undefined`

the returned value is used and it's undefined.

Using the use case you provided, you can modify the usage like this:

iterate(obj, 3600000);

and it will work fine. Or you need to modify iterate to return value. Provide an example of obj so I can write a modification to your iterate function.

Modified the iterate function:

function iterate(obj, delta) {
    obj.forEach(function (element) {
        if (element.hasOwnProperty('unix_time')) {
            element['unix_time'] = parseInt(element['unix_time']) + parseInt(delta);
    return obj;