sotiristherobot
sotiristherobot

Reputation: 299

Could someone please explain me the following with async/await?

could someone please explain this code in depth?

const promiseFactory = () =>
  new Promise(resolve => setTimeout(() => resolve(1), 5000));

If I call this with the following:

const consumer = async() => {
  promiseFactory().then(s => console.log(s));
  console.log("next step");
}

will output "next step" and after 5seconds but if I call it with the following,

const consumer = async() => {
  const val = await promiseFactory();
  console.log(val);
  console.log("next step");
}

will output 1 and then "next step" So in the end promises and async/await are not just a syntax difference?

Upvotes: 0

Views: 62

Answers (2)

Quentin
Quentin

Reputation: 943207

const consumer = async() => {
promiseFactory().then(s => console.log(s));
  console.log("next step");
}
  1. You call promiseFactory
  2. You call `console.log("next step");
  3. At some point in the future the promise resolves and you call console.log(s)
const consumer = async() => {
  const val = await promiseFactory();
  console.log(val);
  console.log("next step");
}
  1. You can promiseFactory
  2. At some point in the future the promise resolves and you call console.log(val) and then console.log("next step")

So in the end promises and async/await are not just a syntax difference?

They, essentially are, you are just not writing equivalent code.

Your use of async and await is equivalent to:

const consumer = async () => {
    promiseFactory().then(s => {
        console.log(s);
        console.log("next step");
    );
};

with all the code after the await in the callback to then, not just the next line.

And your use of then would be equivalent to:

const consumer = async() => {
  doAsyncStuff();
  console.log("next step");
}

const doAsyncStuff = async () {
    const s = await promiseFactory();
    console.log(s)
}

Upvotes: 1

Mike K
Mike K

Reputation: 6481

You're supposed to put the console.log("next step"); into the then of the promise. Javascript doesn't stop execution. With await, you're waiting first, then continuing execution.

const consumer = /* you don't need the async here */ () => {
  promiseFactory().then(s => {
    console.log(s));
    console.log("next step");
  }
}

Upvotes: 0

Related Questions