-1

Why output from code below is Promise {<pending>} instead of Response. What I doing wrong? Also await fetch("https://...") not working.

function asynchronousFunction() {
  return fetch("https://thatcopy.pw/catapi/rest/")
}

const mainFunction = async () => {
  const result = await asynchronousFunction()
  return result;
}
console.log(mainFunction())
zaeraan
  • 151
  • 1
  • 5
  • 3
    Every async function returns a promise. You probably wrote `mainFunction` to get around this, but unfortunately this will not work. – Evert Jun 30 '21 at 17:20
  • 2
    You need to put the `console.log` *inside* the `mainFunction`. You cannot use `async`/`await` to immediately get a value from the future. – Bergi Jun 30 '21 at 17:28
  • So `result = await asynchronousFunction()` get the response and then it is turn back into a promise by `async mainFunction` after return? Do I understand it correctly? ( I mean an example from my code) – zaeraan Jun 30 '21 at 17:34

1 Answers1

1

You shouldn't think of Promises and async functions (which return Promises) as something you can use to return a value at top-level. It's usually a bad idea that comes from the imperative and synchronous programming mindset.

Use chaining instead, either move the console.log inside mainFunction, or write this:

asynchronousFunction()
  .then(console.log)
Guerric P
  • 28,450
  • 6
  • 38
  • 76