How to iterate over an array correctly with asynchronous and synchronous requests inside?

  • 0
    Hello everyone!

    I iterate over an array with objects and, depending on one of the values, either make an asynchronous request to the server, or add another value to the resulting array. Stuck a bit with asynchrony, I need the result array to have the same order as arr . But I get that all asynchronous results go to the end, how can I fix this?

    const arr = [
    {k: true, id: 1},
    {k: false, id: 2},
    {k: false, id: 3},
    {k: true, id: 4},
    {k: false, id: 5},
    {k: false, id: 6},
    {k: true, id: 7}
    ];
    const result = [];
    
    arr.forEach(async ({ k, id }) => {
       if (k) {
          await api.getData(id).then((response) => {
             result.push(response);
         })
       } else {
             result.push(id);
       }
    })
    JavaScript Anonymous, Sep 19, 2020

  • 1 Answers
  • 0
    async function processData(data) {
    const result = [];

    for (const { id, k } of data) {
    result.push(k ? await api.getData(id) : id);
    }

    return result;
    }


    or



    function processData(data) {
    return Promise.all(data.map(({ id, k }) => k ? api.getData(id) : id));
    }
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!