0

My background is mostly python so I'm struggling with this async-await paradigm right now. I understand the flow for simple things, but when it's complicated due to nestedness and chaining multiple sync/async pieces I'm not getting the results I was hoping for. Below is the stub that should sum up where I got stuck

const _ = require('underscore');
const axios = require('axios').default;

const func1 = async () => {
    let myObj = {1: [1, 2, 3], 2: [1, 2, 3], 3: [1, 2, 3]};
    let bigLst = [];
    _.each(Object.entries(myObj), async ([k, lst]) => {
        let rslt = await Promise.all(lst.map(func2));
        bigLst.push(rslt);
    });
    return bigLst; // but bigLst is empty :'(
};

const func2 = async (id) => {
    const rslt = await axios.get(f`https://some-url-${id}.com`);
    return rslt;
};

let final_rslt = func1(); // so is final_rslt

func1 doesn't have to return the final result, I can save it in a db or something like that, but the problem is it's still empty inside of the func1 body after the _.each piece. So my question is - how do I collect results of multiple async calls into a one big object to either return or work with within the function.

Thanks.

Kaster
  • 357
  • 4
  • 16
  • 1
    You already know how to use `await Promise.all(lst.map(…))`. Now do the same for the loop over the `Object.entries(myObj)` and create the `bigLst` like you did `rslt`. – Bergi Apr 04 '22 at 01:49
  • @Bergi thanks but turned out my issue is with the `_.each` part. As soon as I replaced that with `for` loop as it was suggested on linked question everything worked like a charm. – Kaster Apr 04 '22 at 02:47
  • Yes, that's what I said, the `_.each` loop over `Object.entries` is broken (also shown in [the duplicate](https://stackoverflow.com/q/37576685/1048572)). You can use either a normal `for` loop or the concurrent `Promise.all` + `map` approach. – Bergi Apr 04 '22 at 02:52

0 Answers0