Hacker News new | ask | show | jobs
by ctidd 2152 days ago
If I follow your statement, it doesn't appear correct. JS Promises are eager, and the work underlying the promise will begin executing prior to being awaited. Await is just blocking on that execution's resolution.

    // Given:
    const fooPromise = asyncFoo();
    const barPromise = asyncBar();

    // Then this...
    await fooPromise;
    await barPromise;

    // ...is equivalent to this:
    await Promise.all([fooPromise, barPromise]);
Now, Promise.all() is useful, but it is unrelated to when computation starts.
2 comments

This is true and this is the root cause of the misunderstanding from the blog. Promises execute immediately, await blocks on a promise. Promise.all and Promise.allSettled allow you to compose promises and block on a single promise instead of multiple awaits but have nothing to do with executing a promise.

The misunderstanding in the article has to do with misunderstanding when a promise is executed. It’s easy to wonder why calling await on a promise directly vs calling it on a variable containing a promise is different. The difference is promises execute immediately on creation while await blocks on a promise. So a promise that is created after an await will be executed after that awaited promise is resolved.

I can't get it, and from my experience, this is not true.

Consider:

  const x = await foo();
  await bar(x);
How can you schedule `foo()` and `bar()` in parallel, when they have an explicit data dependency?
> How can you schedule `foo()` and `bar()` in parallel, when they have an explicit data dependency?

You can't, but that's a fundamentally different scenario than what's being discussed.