Understanding Asynchronous JavaScript

JavaScript's asynchronous nature can sometimes surprise even seasoned developers. Here's a simple example that demonstrates the subtle intricacies of the event loop and async/await. Let's break down this code:

function foo() {
  console.log('Start');
  Promise.resolve().then(() => {
    console.log('Inside Promise');
  });
  console.log('Outside');
}

foo();
console.log('End');        

?? What’s happening here?

  1. Start is logged immediately when foo() is called.
  2. Promises are placed into the microtask queue, so the console.log('Inside Promise') is deferred until after synchronous tasks complete.
  3. Outside is logged next as part of the synchronous execution of the function.
  4. After foo() finishes, End is logged.
  5. Finally, Inside Promise is logged from the microtask queue, after the call stack is cleared.

Output:

Start
Outside
End
Inside Promise        

Understanding how the event loop and microtasks interact is key to writing efficient, non-blocking code in JavaScript.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了