新聞中心
如果你正在閱讀這篇文章,你可能已經(jīng)理解了 promise 和 async/await 在執(zhí)行上下文中的不同之處。

在 JavaScript 中,promises 和 async/await 是處理異步操作的兩種不同方法。但它們之間關(guān)系密切。
Promise
Promise 是最終導(dǎo)致異步操作完成或失敗的對象。Promise 可以處于三種狀態(tài)之一:待定、已完成或已拒絕。當異步操作完成時,Promise 要么以一個值實現(xiàn),要么以一個錯誤被拒絕。
// Using Promises
function promiseFunction() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Resolved");
}, 2000);
})
}
console.log("Start");
promiseFunction()
.then((result) => {
console.log(result);
console.log("End");
})
.catch((error)=>{
console.log(error)
});
Output:
Start
Resolved
EndAsync/Await
async/await 是 Promise 之上的語法糖。它為編寫異步代碼提供了一種更簡潔的方法,使其更易于閱讀和編寫。使用 async/await,可以編寫看起來與同步代碼相似的異步代碼,而且它在引擎蓋下使用了 Promise。
在 async/await 中, async 關(guān)鍵字用于聲明異步函數(shù)。 await 關(guān)鍵字用于在繼續(xù)執(zhí)行函數(shù)之前等待承諾的解析。 await 關(guān)鍵字只能在 async 函數(shù)中使用。
// Using Async/Await
async function asyncFunction() {
try {
console.log("Start");
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Resolved");
}, 2000);
});
const result = await promise;
console.log(result);
console.log("End");
} catch (error) {
console.error(error);
}
}
asyncFunction()
output:
Start
Resolved
End差異
唯一的區(qū)別在于 promise 和 async/await 的執(zhí)行上下文。
當創(chuàng)建 Promise 并啟動異步操作時,創(chuàng)建 Promise 后的代碼會繼續(xù)同步執(zhí)行。當 Promise 被解析或拒絕時,附加的回調(diào)函數(shù)會被添加到微任務(wù)隊列中。微任務(wù)隊列會在當前任務(wù)完成后,但在下一個任務(wù)從任務(wù)隊列中處理出來之前進行處理。這意味著在創(chuàng)建 Promise 之后的任何代碼都將在執(zhí)行附加到 Promise 的回調(diào)函數(shù)之前執(zhí)行。
另一方面,在使用 async/await 時, await 關(guān)鍵字會使 JavaScript 引擎暫停執(zhí)行 async 函數(shù),直到 Promise 解析或被拒絕。當 async 函數(shù)等待 Promise 解析時,它不會阻塞調(diào)用棧,因此可以執(zhí)行任何其他同步代碼。一旦 Promise 解析完畢, async 函數(shù)將繼續(xù)執(zhí)行,并返回 Promise 的結(jié)果。如果被拒絕,則會拋出一個錯誤值。
本文標題:Promise 和 Async/Await的區(qū)別
網(wǎng)站地址:http://m.fisionsoft.com.cn/article/cdiogsi.html


咨詢
建站咨詢
