0

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?

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
sotiristherobot
  • 259
  • 3
  • 10

2 Answers2

1
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)
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • thanks for the answer, I'm aware of this, my question would be, how can the equivalent code be written to your code block above with async/await? – sotiristherobot Mar 20 '20 at 12:31
0

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");
  }
}
Mike K
  • 7,621
  • 14
  • 60
  • 120