简体   繁体   English

async/await 是异步的还是同步的?

[英]are async/await async or synchronous?

I'm actually diving into the asyc/await part for the first time so I am having a hard time understanding it.我实际上是第一次潜入 asyc/await 部分,所以我很难理解它。

I know that async await is used to make a function run in an async manner but how, because as per the definition, the "await" keyword halts the execution of a function until the promise is resolved, and then executes the leftover code in the function.我知道 async await 用于使函数以异步方式运行,但是如何,因为根据定义,“await”关键字会暂停函数的执行,直到 promise 得到解决,然后执行剩余的代码功能。 Isn't this a synchronous behaviour, because things are getting executed in order as they should be?这不是同步行为吗,因为事情正在按应有的顺序执行?

Feel free to help me out of my confusion or if I am wrong somewhere.如果我在某个地方错了,请随时帮助我摆脱困惑。

Neither.两者都不。

The async and await keywords are tools to manage promises . asyncawait关键字是管理 promises的工具。

Promises are a tool to manage asynchronous code . Promise 是管理异步代码的工具。

If you mark a function as async then:如果将函数标记为async ,则:

  • its normal return value is replaced with a promise that resolves to its normal return value.它的正常返回值被一个解析为正常返回值的承诺所取代。
  • you may use await inside it你可以在里面使用await

If you use await on the left hand side of a promise, then the containing function will go to sleep until the promise settles.如果您在 promise 的左侧使用await ,则包含函数将进入休眠状态,直到 promise 完成。 Execution outside the async function will continue while it sleeps (ie is is not halted ).异步函数之外的执行将在它休眠时继续(即未停止)。

This lets you use syntax that looks like it works on synchronous code to work on asynchronous code.这使您可以使用看起来适用于同步代码的语法来处理异步代码。

It doesn't make synchronous operations asynchronous or vice versa.它不会使同步操作异步,反之亦然。

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

相关问题 function 中的异步/等待同步 - JavaScript - async/await in function synchronous - JavaScript JavaScript 异步/等待逻辑表现为同步 - JavaScript Async/Await logic behaving as synchronous async / await是否不打算用于全局同步? - Is async/await not intended for global synchronous use? 强制异步功能同步,无需等待异步 - Force asynchronous function to be synchronous without async await 如何在同步函数中等待 JavaScript 中的异步调用? - How to await an async call in JavaScript in a synchronous function? 有没有办法用 async/await 而不是 Promise 返回一个值? 作为同步函数做 - Is there a way to return a value with async/await instead of a Promise ? As a synchronous function do 将异步和同步工作与异步/等待和/或 javascript 中的承诺混合在一起 - Mixing asynchronous and synchronous work with async/await and/or promises in javascript Promises - 如何在没有 async / await 的情况下使异步代码同步执行? - Promises - How to make asynchronous code execute synchronous without async / await? 同步函数调用与异步函数调用中的“await”行为 - Behavior of synchronous function call vs “await” on async function call 在 Async/Await 下留下无用的同步代码是一种反模式吗? - Is leaving useless synchronous code under Async/Await an anti-pattern?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM