尽管在函数中更早或更远地具有新值,但变量仍保留原始值

时间:2018-11-02 22:10:46

标签: javascript node.js scope async-await axios

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))

getAsanaData()中,projectsproject.tasks = tasks之后具有新值。

但是,它的原始值是由console.log(projects)return projects之前打印的。

这当然也意味着将返回原始值,而不是必需的新值。

原因是什么,我该如何解决?

1 个答案:

答案 0 :(得分:0)

尝试一下:

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
    }))
}

这将通过对getTasks的异步调用并为每个项目返回。然后,您应该通过Promise.all

来解决所有问题