Mehran
Mehran

Reputation: 16831

Why calling an async function in JS is not blocking?

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?

Upvotes: 0

Views: 78

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118271

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

Upvotes: 2

Related Questions