-1

I have this piece of code which is inside a function that is called by another second function. Now I have no clue, how to return the result to the second function.

(async () => {
        try {
            const response = await axios.get(knockoutCityURL);
            console.log(response.data["1301210"].data.price_overview);
        } catch (error) {
            console.log(error.response.body);
        }
    })();

I would be very happy if you could help me.

Blackcore
  • 69
  • 1
  • 1
  • 4
  • Does this answer your question? [How to return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Sebastian Simon Jun 25 '21 at 15:39
  • There's no `return` in that IIFE hence the "return value" will be `Promise.resolve(undefined)` – Andreas Jun 25 '21 at 15:45

1 Answers1

1

Remove the IIFE, and just return the Axios promise from a simple function, then make your second function async, and await the data.

(Here's a JSFiddle as async/await doesn't work in a snippet)

function fn1() {

  // return axios.get(knockoutCityURL);
  return new Promise((res, rej) => {
    setTimeout(() => res('Hallo'), 2000);
  });
}

async function fn2() {
  const data = await fn1();
  console.log(data);
}

fn2();
Andy
  • 61,948
  • 13
  • 68
  • 95
  • Do you also know how to wait for this promise if the function is called from a nedb query? It looks like this: `dbps.forEach((dbp) => { const URL = getUrlPriceSaleArray(dbp.gameName); if(dbp.users.length > 1) { lines.push(....); } else { lines.push(...); } });` fn2() is in this case getUrlPriceSaleArray() and it will return the promise from fn1() – Blackcore Jun 25 '21 at 16:40
  • No. You're better off writing a new question. Sorry. – Andy Jun 25 '21 at 16:45