How does async-await works in Javascript?

泄露秘密 提交于 2021-02-16 15:29:05

问题


Does making a function async make it asynchronous?

I started using async-await in place of promise chain. I did something like

async function f(){
    let r = await first();
    let d = await sec(r);
    return d;
}

On calling this function I was able to see that all code happened asynchronously. But in some older article I read we can't create asynchronous function in javascript. So does making function async makes it asynchronous.


回答1:


Does making a function async make it asynchronous?

No, it makes it return a promise and will pause the function until a promise resolves when it hits an await statement.

Promises a way of managing asynchronous code, but don't stop synchronous, blocking code being synchronous or blocking.




回答2:


Does making a function async make it asynchronous?

No, it doesn't.

Yes, we can not create asynchronous function in javascript. We can use asynchronous function to execute our code after a asynchronous task but code will be executed in our single thread only.

await is asynchronous in async-await, when compiler reach at await it stops executing and push everything into event queue and continue with synchronous code after async function. Example

function first() {
    return new Promise( resolve => {
        console.log(2);
        resolve(3);
        console.log(4);
    });
}

async function f(){
    console.log(1);
    let r = await first();
    console.log(r);
}

console.log('a');
f();
console.log('b');

Since await is asynchronous thus every other thing before await happens as usual

a
1
2
4
b
// asynchronous happens
3



回答3:


Does making a function async make it asynchronous?

Depends on what you mean by asynchronous.

Let's consider a slightly different version of your code:

async function f(){
    let rPromise = first();
    let dPromise = sec(r);
    let r = await rPromise;
    let dPromise = await dPromise;
    return d;
}

Here because we don't await the first promise until after the second promise is started, the two might be both waited on at the same time (they might not if first() returned a completed promise quickly enough). The two may be doing stuff at the same time. rPromise might complete before dPromise or it might complete after it. However they will only be doing stuff at the same time if what they are doing is something (like waiting on I/O response from a web service) that happens outside of javascript itself.

In some other languages/frameworks we might expect two threads to be running here, possibly on different cores. In javascript there is only one thread and the bit of the code that is actually running in javascript (rather than the web access library that the javascript is waiting for a response from, or the timer that triggers a delay, or whatever) will only ever be running in first() or sec() but never in both at the same time. If what one if them is internally awaiting returns while the other is dealing with what it awaited on, then the further processing won't happen until the other function is finished.

This is asynchronous (the two are not happening in a fixed sequence where one must happen before the other).

It is not though multithreaded, and the actual javascript code in each does not happen at the same time, which is what would be termed asychronous in some other contexts.

But in some older article I read we can't create asynchronous function in javascript.

Well, firstly, until recently we couldn't even create this sort of asynchronous code in javascript until recently, though we could create promises by other means.

Secondly, while it's asynchronous it's not what some people coming from other languages and frameworks would think of as asynchronous, where asynchronicity is primarily delivered through multi-threading which has both abilities javascript lacks, but also pitfalls that it also lacks.




回答4:


Async and Await are just a simple way of writing JavaScript Promises. But, under the covers, JavaScript converts the code to do what it did before Async and Await were introduced.

Under the hood, your code example:

async function f(){
  let r = await first();
  let d = await sec(r);
  return d;
}

really becomes this code:

function f() {
  return first().then(r => sec(r));
}

Or a more detailed example:

function f() {
  return new Promise(
    (resolve, reject) => {
      first().then(
        function(r) {
          return sec(r);
        }
      ).then(
        function(d) {
          resolve(d);
        }
      ).catch(ex) {
        reject(ex);
      }
    }
  );
}

As you can see, your code example is much easier to read. But it can be confusing because it looks like it is synchronous.



来源:https://stackoverflow.com/questions/53721261/how-does-async-await-works-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!