Why is my async function returning a pending promise after await?

4

I must be missing something here because I do not understand why my promise is not resolving.

I boiled the code down to this simple example:

  ...
  console.log("before");
  const promise = second();
  console.log("after");
  console.log(promise);
  ...

async function first() {
  const p1 = await axios.get("https://<url>");
  console.log("first");
  console.log(p1.data);
  return (p1);
}

async function second() {
  const p2 = await first();
  console.log("second");
  console.log(p2.data);
  return (p2);
};

Which produces this output in the console:

before
after
Promise { <pending> }
first
p1.data
second
p2.data

My understanding is that await pauses execution until it completes before moving to the next line, but that is clearly not happening.

The initial block completes with a pending promise, and then the awaited code in the async functions executes instead of pausing.

What am I missing to make my code pause and wait until the await lines complete with a resolved promise before continuing?

answered question

await for second()

1 Answer

2

You need to await the second so that after the promise is resolved you get the result.

console.log("before");
const promise = await second();
console.log("after");
console.log(promise);

posted this

Have an answer?

JD

Please login first before posting an answer.