There are several asynchronous methods in the node.js for loop. How to execute the following commands after all the asynchronous methods are finished?

in the for loop, how to get the data asynchronously through mongoose, and how to execute the following commands after all the asynchronous methods are finished.

pseudo code is as follows:

function getData (list) {
    let result = []
    
    list.forEach((item) => {
        if (item.type === 1) {
            //
            result.push(x)
        } elseif (item.type === 2) {
            //
            result.push(y)
        } else {
            //
            result.push(z)
        }
    })
    
    return result
}

function main () {
    // 
    let result = getData (list)
}

after execution, the result data is all empty, mainly due to the fact that the asynchronous task has not yet been executed. How to solve this problem?


async/await learn about

async function main () {
    let result = await getData (list); // getDataasync/await
}

1, new method of async/await, es7
2, promise.all
3, series method of async module

Menu