Function keep initialising local variable instead of using existing variable

51 Views Asked by At

I'm new in javascript and I'm trying to get a bunch of task from different projects from todoist and trying to assign a label for those tasks.

const task_list = {};
for (let id of project_id) {
    api.getTasks({
        projectId: id, filter: "(today | overdue | p1) & !subtask"
    })
        .then((tasks) => { Object.assign(task_list, { id: tasks }); console.log(task_list)})
        .catch((error) => console.log(error))
        
}

for (let id of project_id) {
    console.log(id)
    console.log(task_list.id)
}

This is currently my draft for the code. The console.log in the for loop at the bottom is printing undefined but the console.log behind the Object.assign is able to print out the correct output.

Please help.

1

There are 1 best solutions below

1
skmail On BEST ANSWER

You are replacing the id key of task_list object for every iteration , because Object.assign copies the keys and values from an object to the target object which is task_list in your case.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

if you are trying to create a hash table to keep track of all tasks by id

you could mutate the task_list and assign it by id

task_list[id] = tasks

or replace the original task_list using Object.assign

const new_task_list = {}
new_task_list[id] = tasks

task_list = Object.assign(task_list, new_task_list)

or using es6 syntax

Object.assign(task_list,{[id]:tasks})

inside your later loop you can access the task value using the id key

for (let id of project_id) {
    console.log(task_list[id].id)
}

also, the last loop will print an empty object because it will get executed before api.getTasks completed the request, you would need to create an array to save all promises then use

Promise.all(promises).then(() => {
// your loop here
})

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all