0

Take a look at the following code:

function promised() {
    return new Promise((resolve) => {
        setTimeout(() => resolve('Timeout'), 1000);
    });
}

async function awaited()
{
  const r = await promised();
  console.log('Line 10: ' + r);
  return r;
}

function start() {
  const r = awaited();
  console.log('Line 16: ' + r);
}

start();

console.log("All done");

When you run this code, you'll get:

Line 16: [object Promise]
All done
Line 10: Timeout

But I was expecting to get:

Line 10: Timeout
Line 16: Timeout
All done

My expectation was that await should have blocked the execution on line 9. But it seems it does not! My question is why?

3
  • 1
    awaited execution pauses, start's does not as it is not an async method with an await statement. Async methods don't ever block, that is their main purpose to not block. Synchronous functions block, hence why it is advised not to use methods like sync ajax requests. Commented Aug 17, 2018 at 18:00
  • 5
    Possible duplicate of Understanding Async/Await patterns in JavaScript Commented Aug 17, 2018 at 18:01
  • 1
    If you really want to behave the code like synchronous code (what you call blocking), you would've to use async for all functions up to the calling function and await the result of the those async functions. Commented Aug 17, 2018 at 18:21

1 Answer 1

2

You need to write your code as:

    function promised() {
      return new Promise(resolve => {
        setTimeout(() => resolve("Timeout"), 1000);
      });
    }
    
    async function awaited() {
      const r = await promised();
      console.log("Line 10: " + r);
      return r;
    }
    
    function start() {
      const r = awaited();
      // r here is a promise, so you need to call then to wait until
      // awaited is finished.
      return r.then(d => console.log("Line 16: " + d));
    }
    
    start().then(() => console.log("All done"));

result:

// Line 10: Timeout

// Line 16: Timeout

// All done

Sign up to request clarification or add additional context in comments.

10 Comments

Thanks for the post, but it seems async and await are just fancy words for the same Promise concept. They are not blocking at all!!!
@Mehran No. const r = await promised(); this line pauses until it is done. console.log("Line 10: " + r); will not be executed until it is done. With promise, console.log("Line 10: " + r); will be executed.
@Mehran: That's basically right. async/await are just syntactic sugar on top of promises.
It would be nice to extend the answer to include an answer for 'why', so it helps for future Googlers.
@dereli which "why" part?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.