[英]JS Promises: Why does await have to be inside an async function?
假設我有以下代碼:
new Promise(res => res(1))
.then(val => console.log(val))
我可以像這樣使用async/await
來實現相同的目標:
let func = async () => {
let val = await new Promise(res => res(1))
console.log (val)
}
func()
我將async/await
代碼放在 function 中,只是因為您必須在異步 function 中才能使用await
。
我想知道的:為什么要執行此規則? 只是做會有什么問題
let val = await new Promise(res => res(1))
console.log (val)
Is the reason that await
causes the current scope to pause execution, and so forcing you to put the async/await
code inside the special scope of an async function prevents JS from pausing the execution of all the rest of your code?
async
function 是不同類型的 function。 它總是返回 promise。 At the point of the first await
that it hits, the function execution is suspended, the async function returns that promise and the caller gets the promise and keeps executing whatever code comes next.
In addition, the async
function automatically wraps its function body in a try/catch
so that any exceptions whether synchronous or unhandled rejected promises from an await
are automatically caught by the async
function and turned into a rejection of the promise they automatically return.
而且,當您從async
function return
一個值時,該返回值將成為它返回的 promise 的解析值。
我想知道的:為什么要執行此規則? 只是做會有什么問題...
async
function 具有許多常規 function 沒有的行為,並且 JS 解釋器想提前知道哪種類型的 ZC1C425268E68385D1AB5074C17A94F1 可以正確執行它,所以它可以正確執行它。
I suppose it might have been possible for the interpreter to have discovered when compiling the function body that it contains an await
and automatically given the surrounding function an async
behavior, but that's not very declarative and simply adding or removing one await
could change how the function完全有效。 只是我的猜測,但語言設計者認為強制async
function 以這種方式聲明要好得多,而不是根據 function 主體的內容推斷其行為。
這里的大局是要了解async
function 的工作方式不同:
而且,如果在聲明中使用async
關鍵字而不是從 function 正文中推斷出單獨的行為,那么語言會更清晰、更具聲明性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.