0

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.

Vector
  • 5
  • 1

1 Answers1

1

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

skmail
  • 408
  • 3
  • 6
  • I see, it turns out that issue I'm having is that I did not understand how promises works in javascript. I thought that my code would execute line-by-line, which is not happening here. But yeah the way you assign object is correct. – Vector Feb 04 '22 at 08:17