简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM