I have an array of objects called projects. Each project has a project_id. I need to retrieve all members assigned to a project from the DB using the project_id, check if each member is approved, and then populate a dropdown select with the project titles.
Since I need to wait for the GET request to complete before the other tasks, I wrapped the request in a promise. Unfortunately, I can't use async await because our team uses promises as the standard. For each project object in the array, I need to execute this promise and chain it with .then() to check the approval statuses and fill the dropdown.
This is what I have so far:
var select = document.getElementById('projectSelect')
projectArray.map(project => () => { // map each project in array to a new promise
getMembers(project.project_id)
.then(members => { // pass in array of member objects returned from getMembers()
if (members.every(member => member.approved)) {
// populate dropdown with projects
let option = document.createElement("option")
option.text = project.title
option.value = project.project_id
select.appendChild(option)
}
}
})
function getMembers(project_id) {
return new Promise((resolve, reject) => {
$.ajax({
type: "GET",
url: "../../../getMembers",
data: {
"project_id": project_id
},
success: function (data) {
return resolve(data)
},
error: function (error) {
return reject(error)
}
})
}
}
The functions inside the .map() are not run so I'm not sure if I have to call them again. How do I run this promise and the following function in order? I want to complete those steps for the first project, before moving to the next project. I would appreciate any suggestions, thanks!
Using
Promise.allinstead of waiting for each promise to get resolved is a better approach. Here's my solution: