For each object in array, how to resolve promises that retrieve DB data and populate dropdown in sequential order?

86 views Asked by At

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!

1

There are 1 answers

1
Sunny Gandhwani On

Using Promise.all instead of waiting for each promise to get resolved is a better approach. Here's my solution:

const promises = projectArray.map(project => getMembers(project.project_id));

Promise.all(promises)
    .then(arrayOfMembersArrays => {
        // arrayOfMembersArrays is an array of arrays, where each inner array contains members for a specific project

        if (arrayOfMembersArrays.every(members => members.every(member => member.approved))) {
            // Populate dropdown with projects
        }
    })

function getMembers(project_id) {
    return new Promise((resolve, reject) => {
        // TODO: Add AJAX GET request
        
        // Resolve with result
        resolve(result);
    });
}