简体   繁体   English

async-await如何在Javascript中工作?

[英]How does async-await works in Javascript?

Does making a function async make it asynchronous? 使函数异步是否使其异步?

I started using async-await in place of promise chain. 我开始使用async-await代替Promise链。 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. 但是在一些较老的文章中,我读到我们无法在javascript中创建异步函数。 So does making function async makes it asynchronous. 使函数异步也会使其异步。

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. 不,它使它返回一个promise,并将暂停该功能,直到promise到达await语句时,promise解析。

Promises a way of managing asynchronous code, but don't stop synchronous, blocking code being synchronous or blocking. 承诺了一种管理异步代码的方法,但不要停止同步,阻止代码被同步或阻止。

Does making a function async make it asynchronous? 使函数异步是否使其异步?

No, it doesn't. 不,不是。

Yes, we can not create asynchronous function in javascript. 是的,我们无法在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. async在async- await是异步的,当编译器到达await时,它将停止执行并将所有内容推送到事件队列中,并在async函数之后继续执行同步代码。 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

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). 在这里,因为我们要等到第二个承诺开始后才await第一个承诺,所以这两个都可能同时等待(如果first()足够快地返回完成的承诺,它们可能不会同时等待)。 The two may be doing stuff at the same time. 两者可能同时做事。 rPromise might complete before dPromise or it might complete after it. rPromise可能在dPromise之前完成,也可能在dPromise之后完成。 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. 但是,只有当他们正在做的事情(例如等待来自Web服务的I / O响应)发生在javascript本身之外时,他们才会同时在做事情。

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. 在javascript中,只有一个线程,而实际上在javascript中运行的代码只有一点(而不是javascript正在等待响应的Web访问库,触发延迟的计时器等),在first()sec()运行,但不能同时在两者中运行。 If what one if them is internally await ing returns while the other is dealing with what it await ed on, then the further processing won't happen until the other function is finished. 如果一个在内部await返回,而另一个正在处理await东西,那么在另一个函数完成之前,不会进行进一步的处理。

This is asynchronous (the two are not happening in a fixed sequence where one must happen before the other). 这是asynchronous (两者不是按固定的顺序发生的,其中一个必须先发生在另一顺序之前)。

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. 它不是多线程的,并且每个线程中的实际javascript代码不会同时发生,在其他情况下,这也称为asychronous

But in some older article I read we can't create asynchronous function in javascript. 但是在一些较老的文章中,我读到我们无法在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. 好吧,首先,直到最近,我们甚至直到最近都无法在javascript中创建这种异步代码,尽管我们可以通过其他方式创建promise。

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. 其次,虽然它是异步的,但不是来自其他语言和框架的人会认为它是异步的,异步性主要是通过多线程实现的,而多线程既具有javascript所缺乏的功能,也具有它所缺乏的陷阱。

Async and Await are just a simple way of writing JavaScript Promises. Async和Await只是编写JavaScript Promises的一种简单方法。 But, under the covers, JavaScript converts the code to do what it did before Async and Await were introduced. 但是,在幕后,JavaScript会将代码转换为执行引入Async和Await之前的代码。

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. 但这可能会造成混淆,因为它看起来是同步的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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