'Return result after the forEach loop

I have this function that returns a list, but the list stays empty even after I add items to the list in the forEach. So I tried using Promises, but I need a little help. Right now the result is "undefined". How do I return the result list after the forEach loop is done?

async function return_list() {
    var result = [];

    var list_of_skus = [...];

    var promise = new Promise(() => {
        list_of_skus.forEach((number) => {

          api.get(...)
          //api request

          result.push(api_data)
        });
    });

    promise.then({
        return result;
    })
}

edit: i changed the code a bit: In the forEach loop im using an api request to get some data, and then add an item the result list



Solution 1:[1]

Here you can find a bit more information about promises: Promises MDN

As long as you do nothing async (like network requests etc) you probably don't need promises in your forEach.

This should work:

function return_list() {
    const result = [];

    const list_of_skus = [...];

    list_of_skus.forEach((number) => {
        result.push(1)
    });

    return result;
}

If you need promises, this would work:

async function return_list() {
    const list_of_skus = [...];

    const promises = list_of_skus.map(async (number) => {
        return await somethingAsync(number)
    });

    return await Promise.all(promises)
}

As you transform every sku list item, you can use a map to transform all skus into a promise which does something async. Using Promise.all() it is possible to execute the promises in parallel.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Simolation