0

In Express I have an array of projects, with each project containing an array of workSessions stored as Mongo ObjectIds.

I want to iterate over the array of projects, and for each project get its workSessions from MongoDB, then add the list of workSessions to an object which will end up containing all the workSessions from all the projects in the projects array.

projectService.GetWorkSessions(result.user._id)
  .then((projects) => {
    console.log(projects) // nothing gets logged.
  }

GetWorkSessions: (userId) => {
  return getProjects(userId) // this is ok.
    .then((projects) => {
      let workSessions = {};
      let counter = 0;
      return promise = new Promise((resolve, reject) => {
        return projects.forEach((project) => {
          return getWorkSessions(project)
            .then((sessionsList) => {
              counter ++
              workSessions[project._id] = sessionsList;
              if(counter == projects.length) {
                console.log('done')
                promise.resolve();
              }
            })
        })
      })
    })
},

The workSession object gets populated, but how do I return it to the calling function once the forEach has completed?

1
  • promise = new Promise ... promise.resolve() - no ... that's not how Promises work Commented Nov 28, 2017 at 8:26

1 Answer 1

1

When you want to map an array of values to an array of asynchronously-retrieved values, use Promise.all(values.map(...)):

const projectWithSessions = (project) =>
    getWorkSessions(project).then((sessions) => 
        ({ project, sessions })
    );

GetWorkSessions: (userId) => 
    getProjects(userId).then((projects) => 
        Promise.all(projects.map(projectWithSessions))
    );

The return value of GetWorkSessions() should resolve to an array of objects each with a .project and .sessions property.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.