0
let getProjects = function() {
  try {
    return axios.get('https://app.asana.com/api/1.0/projects/')
  } catch (error) {
    console.error(error)
  }
}

let getTasks = function(project) {
  try {
    return axios.get('https://app.asana.com/api/1.0/projects/'+project+'/tasks')
  } catch (error) {
    console.error(error)
  }
}

async function getAsanaData() {
    let projects = await getProjects()
    projects = projects.data.data
    projects.map(async (project) => {
        //project.attachments = []
        let tasks = await getTasks(project.gid)
        if(tasks != undefined){
          tasks = tasks.data.data 
          project.tasks = tasks
          //console.log(projects)
        }
    })
    console.log(projects)
    return projects
}

Promise.try(() => {    
  return getAsanaData();
}).then((result) => {
  //console.log(util.inspect(result, {showHidden: false, depth: null}))
  //var asanaData = safeJsonStringify(result);
  //fs.writeFile("thing.json", asanaData);
})
.catch(err=>console.log(err))

In getAsanaData(), projects has a new value after project.tasks = tasks.

However, it's original value is printed by console.log(projects) before return projects.

This of course also means that the original value rather than the necessary new value will be returned.

What is the cause and how do I resolve this?

Gabriel Rivera
  • 175
  • 1
  • 1
  • 6
  • 1
    `Array.map()` returns a new array, it does not modify it in place. – pmkro Nov 02 '18 at 22:14
  • When are you looking at the log? Since you're updating the object, every time through the loop, and the console contains a live reference to the object, it will change depending on when you expand it. – Barmar Nov 02 '18 at 22:17
  • See https://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays – Barmar Nov 02 '18 at 22:18
  • @Barmar The log after project.tasks = tasks indicates that the projects have the tasks arrays added. The log before return as well as the JSON file that's later written show projects without tasks arrays added. – Gabriel Rivera Nov 02 '18 at 22:45
  • @pmkro So now if I set projects = to the new array and then try to return projects, I get nothing but pending promises. – Gabriel Rivera Nov 02 '18 at 23:06

1 Answers1

0

Try this:

async function getAsanaData() {
    let projects = await getProjects()
    return Promise.all(projects.data.data.map(async (project) => {
        let tasks = await getTasks(project.gid)
        project.tasks = !!tasks ? tasks.data.data : project.tasks            
        return project
    }))
}

This will go through the async calls to getTasks and return for each the project. Then you should get them all resolved via Promise.all

Akrion
  • 18,117
  • 1
  • 34
  • 54