0

I am returning ASANA's api and trying to push that data into an array. But when I try to console.log array outside the loop it's being empty. I guess I am missing something, but couldn't figure it out.

it's the code block.

let tasks = [];

$.each(projectArray, function(key,project){
    asana.request("GET", "projects/"+project+"/tasks?opt_pretty&opt_expand=(this%7Csubtasks%2B)", function(err, response){
        response.data.forEach((element, key) => {
            if (element.completed === true) {

                let taskObj = {
                    title: element.name,
                    works: "",
                    price1: "",
                    price2: "",
                }

                element.custom_fields.forEach(elem => {
                    if (elem.name === "com_name") {
                        taskObj.works = elem.text_value                                                    
                    } else if (elem.name === "price1") {
                        taskObj.price1 = elem.number_value
                    } else if (elem.name === "price2") {
                        taskObj.price2 = elem.number_value
                    }                        
                })

                tasks.push(taskObj) // data pushed. 
            }
        })
    })

    console.log(tasks) // i can log the data 'till here.
})

var maskedTasks = JSON.parse(JSON.stringify(tasks))

console.log(maskedTasks)
//can't log the data outside of the loop. array is being empty.

I tried to stringify and parse it. But it doesn't work...

yvl
  • 620
  • 7
  • 25
  • `asana.request()` is asynchronous. – Barmar Jan 02 '20 at 07:25
  • you have an asynchronous function. `maskedTasks` is logged outside the loop, before the data is even pushed into the array. – BlackPearl Jan 02 '20 at 07:26
  • @BlackPearl that's quite a hint thank you. I am not sure this is the right way to solve it, but I implement a `setTimeout()` and solved the issue. – yvl Jan 02 '20 at 07:33
  • That's not the right way to solve it. https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron has some very good answers on how to tackle this. – BlackPearl Jan 02 '20 at 07:42

0 Answers0