Reputation: 299
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
Reputation: 943207
const consumer = async() => { promiseFactory().then(s => console.log(s)); console.log("next step"); }
promiseFactory
console.log(s)
const consumer = async() => { const val = await promiseFactory(); console.log(val); console.log("next step"); }
promiseFactory
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
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