javascript的异步功能实际上是同步的吗? [英] Are javascript's async functions actually synchronous?

查看:49
本文介绍了javascript的异步功能实际上是同步的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚异步代码如何在Javascript中工作.现在,我了解到JS中实际上只有一个线程执行队列中的作业,并且只有在当前作业完成时(即,如果所有同步代码或异步函数都已完成),它才可以开始执行下一个作业.

I am trying to figure out how does asynchronous code work in Javascript. Now, I understand that there is actually one single thread in JS that executes jobs in a queue, and it can only start executing the next job if the current one is completed (i.e. if all of the sync code or an async function is completed).

现在,令人困惑的部分是实际上算作异步函数的东西-实际放入队列中的单独作业中的内容,而没有放入

Now, the confusing part is what actually counts as an asynchronous function - what actually gets put into a separate job in the queue, and what doesn't.

首先,我们对函数使用 async 关键字.那么这是否意味着这些功能将被放入队列中的单独作业中,并在将来的某个位置执行?好吧,事实证明答案是.但是,请耐心等待,正如我将要解释的.

For start, we have the async keyword for functions. So does that mean those functions will be put into a separate job in the queue and be executed somewhere in the future? Well, actually it turns out the answer is NO. But bear with me, as I will explain.

据我了解,从理论上讲,JS线程应该首先执行所有同步代码,直到完成为止,同时通过将所有异步函数,promise和回调函数作为作业放置到末尾来延迟所有异步函数,promise和回调的执行.队列.然后,一旦所有同步代码完成,它将开始执行所有堆积的工作.

As far as I understand, in theory, the JS thread is supposed to begin by executing all synchronous code until it completes, while delaying the execution of all async functions, promises and callbacks by placing them as jobs to the end of the queue. Then, once all sync code completes, it will start doing all those jobs that got piled up.

所以,如果我有以下代码:

So if I have the following code:

async function asyncFunc() {
    console.log("executing async function");
}

console.log("starting sync code");
asyncFunc().then(() => {
    console.log("executing callback of async function")
});
console.log("sync code completed");

那么从理论上讲,它应该首先执行所有同步代码,然后才开始执行async函数,然后执行回调:

Then in theory, it should execute all sync code first, and only then start executing the async function and then the callback:

starting sync code
sync code completed
executing async function
executing callback of async function

但是现实是不同的!实际上,它实际上与其他同步代码一起同步执行异步功能 .真正放入作业队列的唯一位是异步函数的回调:

But the reality is different! In reality, it actually executes the async function synchronously, together with the rest of the sync code. The only bit that actually gets put into the job queue is the callback of the async function:

starting sync code
executing async function
sync code completed
executing callback of async function

那是什么意思?那个 async 函数实际上是一个谎言吗?看起来如此,因为它们实际上是正常,同步函数,您可能碰巧将 async 回调附加到该函数.

So what does that mean? That async functions are actually a lie? It seems so, as they are actually normal, synchronous functions that you can happen to attach an async callback to.

现在,我知道 async 实际上是返回 Promise 的函数的语法糖,例如:

Now, I know that async is actually a syntactic sugar for a function that returns a Promise, such as:

async function asyncFunc() {
    console.log("executing async function");
}

是以下语言的语法糖:

function asyncFunc() {
    return new Promise((resolve) => {
        console.log("executing async function");
        resolve();
    });
}

但是我的观点仍然存在.您传递给promise的所谓异步函数实际上是同步执行的.好吧,从技术上讲, Promise 对象并不意味着它将异步执行,但是 async 关键字却可以!因此,它是完全错误的信息,它使您相信它是异步的,而事实证明并非如此.

But my point still remains. The supposedly-async function that you pass into the promise actually is executed synchronously. Well, technically the Promise object doesn't imply that it will be executed asynchronously, but the async keyword does! So it's outright false information, it makes you believe that it's asynchronous, when it demonstrably isn't.

推荐答案

就像构造Promise一样,在 async 函数中进行同步的任何内容都在任何 await 之前s 会同步执行. async 函数仅在遇到 await 后才会停止执行其代码-直到那时,它也可能是正常的非 async 函数(除了它将返回值包装在Promise中的事实).

Just like when constructing a Promise, anything synchronous inside an async function before any awaits are encountered will execute synchronously. An async function will only stop executing its code once it encounters an await - until then, it may as well be a normal non-async function (except for the fact that it'll wrap the return value in a Promise).

async function asyncFunc2() {
  console.log("in Async function 2");
}
async function asyncFunc1() {
  console.log("in Async function 1");
  await asyncFunc2();
  console.log('After an await');
}
console.log("starting sync code");
asyncFunc1().then(() => {
  console.log("Received answer from async code");
});
console.log("finishing sync code");

如您在上面的代码段中所见,主线程仅在 asyncFunc1 await (以及所有<该 await )调用的em> synchronous 代码已完成.

As you can see in the snippet above, the main thread only resumes outside of asyncFunc1 once asyncFunc1's await (and all synchronous code invoked by that await) is complete.

async 是一个关键字,允许您在函数内部使用 await ,但它并不是本质上的意思,-只是一个关键字.函数甚至可以同步运行其所有代码(尽管有点奇怪).

async is a keyword that allows you to use await inside of a function, but it doesn't intrinsically mean anything else, really - it's just a keyword. The function may even run all of its code synchronously (though that'd be kind of weird to see).

这篇关于javascript的异步功能实际上是同步的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆