Promise 和 Async/Await的區(qū)別
如果你正在閱讀這篇文章,你可能已經(jīng)理解了 promise 和 async/await 在執(zhí)行上下文中的不同之處。
在 JavaScript 中,promises 和 async/await 是處理異步操作的兩種不同方法。但它們之間關(guān)系密切。
Promise
Promise 是最終導(dǎo)致異步操作完成或失敗的對(duì)象。Promise 可以處于三種狀態(tài)之一:待定、已完成或已拒絕。當(dāng)異步操作完成時(shí),Promise 要么以一個(gè)值實(shí)現(xiàn),要么以一個(gè)錯(cuò)誤被拒絕。
// 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
End
Async/Await
async/await 是 Promise 之上的語(yǔ)法糖。它為編寫異步代碼提供了一種更簡(jiǎn)潔的方法,使其更易于閱讀和編寫。使用 async/await,可以編寫看起來(lái)與同步代碼相似的異步代碼,而且它在引擎蓋下使用了 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í)行上下文。
當(dāng)創(chuàng)建 Promise 并啟動(dòng)異步操作時(shí),創(chuàng)建 Promise 后的代碼會(huì)繼續(xù)同步執(zhí)行。當(dāng) Promise 被解析或拒絕時(shí),附加的回調(diào)函數(shù)會(huì)被添加到微任務(wù)隊(duì)列中。微任務(wù)隊(duì)列會(huì)在當(dāng)前任務(wù)完成后,但在下一個(gè)任務(wù)從任務(wù)隊(duì)列中處理出來(lái)之前進(jìn)行處理。這意味著在創(chuàng)建 Promise 之后的任何代碼都將在執(zhí)行附加到 Promise 的回調(diào)函數(shù)之前執(zhí)行。
另一方面,在使用 async/await 時(shí), await 關(guān)鍵字會(huì)使 JavaScript 引擎暫停執(zhí)行 async 函數(shù),直到 Promise 解析或被拒絕。當(dāng) async 函數(shù)等待 Promise 解析時(shí),它不會(huì)阻塞調(diào)用棧,因此可以執(zhí)行任何其他同步代碼。一旦 Promise 解析完畢, async 函數(shù)將繼續(xù)執(zhí)行,并返回 Promise 的結(jié)果。如果被拒絕,則會(huì)拋出一個(gè)錯(cuò)誤值。