0

I'm trying to get an array from [getAll].
It must wait for two axios functions, so there are two awaits as you can see.
The problem is, array [A] keep returns nothing but undefined members like [undefined, undefined, undefined, undefined, undefined].
I've checked that [getItem] gets the exact data that what I intended.
So, I think there's something wrong with [getAll]; such as await getItem(Name) but I cannot find out what it is.
[console.log("res1: "+res1);] just prints [res1: undefined].
Thank you for your suggestions.

const getItem = async (Name) => {
  await axios
  .get(url1+Name)
  .then(async (res1) => {
    const url3 = url2+res1;
    await axios
      .get(url3)
      .then((res2) => {
        console.log(res2.data);
        return res2.data;
      });
  });
};

const getAll = async (Arr) => {
  const A=[];
  for (const Name of Arr) {
    await getItem(Name)
      .then((res1) => {
        console.log("res1: "+res1);
        A.push(res1);
      });
  }
  return A;
}

router.post("/", async (req, res) => {
  res.send(await getAll(req.body.Names));
});
John99
  • 47
  • 5
  • You can use Promise.all() to handle array of promises – Nikita Mazur Jul 28 '21 at 08:37
  • 1
    Also consider not to use .then() when you use async/await – Nikita Mazur Jul 28 '21 at 08:39
  • 1
    @ John99 - The problem is that your `getItem` function doesn't *return* anything. You have a `return` in a `then` callback, but `getItem` doesn't have a `return`. In general, don't mix calls to `.then` and `.catch` with `async`/`await`, the purpose of `async`/`await `is to make using promises simpler. Change `getItem` to: `const getItem = async (name) => { const res1 = await.axios(url1 + name); const url3 = url2 + res1; const res2 = await axios.get(url3); return res2.data; };` – T.J. Crowder Jul 28 '21 at 08:40
  • Similarly, in `getAll`: `const getAll = async (arr) => { const result = []; for (const name of arr) { result.push(await getItem(name)); } return result; };` if you really want those requests done in *series*. If you want them in parallel: `const getAll = async (arr) => Promise.all(arr.map(getItem));` (or `arr.map(name => getItem(name))`). – T.J. Crowder Jul 28 '21 at 08:41
  • (Side note: Is `url3 = url2 + res1` really correct? You don't need `.data` on `res1`?) – T.J. Crowder Jul 28 '21 at 08:47
  • Oops, I have `await.axios(` instead of `await axios.get(` above, sorry about that. – T.J. Crowder Jul 28 '21 at 08:52

0 Answers0