1
votes

Since async function is non-blocking, I expected asyncfunc in below code does not block and console.log(a) prints zero.

var a = 0;
const asyncfunc = async () => {
  for (let i = 0; i < 1000000000; i++) {}
  a = 1;

  return 2;
};

const asyncmain = async () => {
  a = asyncfunc();
  console.log(a);

  return true;
};

asyncmain();

But when I executed, all code in asyncfunc ran first and then console log is written. function is blocked at async function first!

expected : 0 actual : Promise { 2 }

I cannot understand this result. help me to understand this result!

ps I ran this code on node.js v10.15.3

1
"Since async function is non-blocking' this is not correct. Async functions will run synchronously until they hit an await. - VLAZ
Simply put, putting the async keyword in front of a function simply means whatever value that function returns will be wrapped in a Promise. - Adam

1 Answers

0
votes

If you want to use results from an asynchronous function, you must specify that you want to wait to have them to use it, using the await clause.

var a = 0;
const asyncfunc = async () => {
  for (let i = 0; i < 1000000000; i++) {}
  a = 1;

  return 2;
};

const asyncmain = async () => {
  a = await asyncfunc();
  console.log(a);

  return true;
};

asyncmain();

I recommend that you read this article to fully understand the behavior of asynchronous functions.