简体   繁体   中英

What is the execution flow of an await/async program in TypeScript/JavaScript or Python?

For a while know I try to wrap my head around the internals of async/await. I am a C++ developer with focus on multithreading and this concepts interferes with how a C++ program is executed.

I do understand Promise objects, and the emphasis of concurrent,= parallelism. and also the event loop? I can follow the demand to have a single-threaded application that concurrently executes different parts of the program but what "creates" an event on the event loop? Is it the Promise object? Or the async keyword? Or is it something in some I/O functions to not block?

The closest concept I know would be the Global Interpreter Lock in Python where several threads wait for a global lock, so Python executes in a round-robin method to let every thread execute a piece of code. But this concept doesn't require an event-loop, and eg in JS/TS there is only a single thread involved.

Can anyone help me out (or recommend a good resource), so I can understand the execution flow or how I can make sense of this? Thank you so much!

If you understand a promise then async await is just syntactic sugar.

async function() {
  doStuff();
  const x = await getSomePromise();
  doStuffWithX(x);
}

is the same as

function() {
  doStuff();
  getSomePromise().then(function(data) {
    const x = data;
    doStuffWithX(x);
  });
}

The interpreter does the callback wrapping for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM