如何使用async await使JavaScript变成异步?

huangapple go评论71阅读模式
英文:

How async await makes javascript asynschronous?

问题

JavaScript是同步的,所以我们使用回调、Promise和async/await来使其异步化。但是,当我们使用async/await时,它会等待await语句完成后才继续执行下一个语句,所以从技术上讲,这是同步的。那么为什么说async/await用于使JavaScript异步呢?请告诉我是否有什么我没有理解的地方。

我查了很多资源,但仍然不太清楚。

英文:

As javascript is synchronous, so we use callback promises and async await to make it asynchronous, but when we use async await it wait for the await statement to be completed before going to next statement, so technically this is synchronous then why it is written that async await is used to make javascript asynchronous. Please let me know if I am missing something

I checked many resouces but still its not clear to me

答案1

得分: 2

Sure, here are the translated parts:

How async await makes javascript asynschronous?

它不会。它是用来管理已经是异步的代码的工具。

As javascript is synchronous

它不是。它运行一个单一的主事件循环,并有规则来处理在该循环之外处理的情况。

when we use async await it wait for the await statement to be completed before going to next statement, so technically this is synchronous

包含 await 语句的函数会等待直到 await 语句右侧的 Promise 解析完成,而且主事件循环有空闲时,才会继续执行该函数。

包含 await 语句的函数必须标记为 async,这使它们返回一个 Promise。

主事件循环会在调用带有 async 标记函数的函数之外继续处理,而调用函数可以访问由标记为 async 的函数返回的(未解析的)Promise。

英文:

> How async await makes javascript asynschronous?

It doesn't. It is a tool to manage code that is already asyncronous.

> As javascript is synchronous

It isn't. It runs a single main event loop and has rules for when stuff is handled outside of that loop.

> when we use async await it wait for the await statement to be completed before going to next statement, so technically this is synchronous

The function containing the await statement goes to sleep until the promise (on the RHS of the await statement) resolves and the main event loop is free to pick the function up again.

Functions containing await statements must be marked with the async keyword which makes them return a promise.

The main event loop continues processing outside of that function where the calling function has access to the (unresolved) promise returned by the function marked as async.

huangapple
  • 本文由 发表于 2023年1月3日 18:01:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/74991746.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定