Promise 和 Async/Await的區別
如果你正在閱讀這篇文章,你可能已經理解了 promise 和 async/await 在執行上下文中的不同之處。
在 JavaScript 中,promises 和 async/await 是處理異步操作的兩種不同方法。但它們之間關系密切。
Promise
Promise 是最終導致異步操作完成或失敗的對象。Promise 可以處于三種狀態之一:待定、已完成或已拒絕。當異步操作完成時,Promise 要么以一個值實現,要么以一個錯誤被拒絕。
// 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 之上的語法糖。它為編寫異步代碼提供了一種更簡潔的方法,使其更易于閱讀和編寫。使用 async/await,可以編寫看起來與同步代碼相似的異步代碼,而且它在引擎蓋下使用了 Promise。
在 async/await 中, async 關鍵字用于聲明異步函數。 await 關鍵字用于在繼續執行函數之前等待承諾的解析。 await 關鍵字只能在 async 函數中使用。
// 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
差異
唯一的區別在于 promise 和 async/await 的執行上下文。
當創建 Promise 并啟動異步操作時,創建 Promise 后的代碼會繼續同步執行。當 Promise 被解析或拒絕時,附加的回調函數會被添加到微任務隊列中。微任務隊列會在當前任務完成后,但在下一個任務從任務隊列中處理出來之前進行處理。這意味著在創建 Promise 之后的任何代碼都將在執行附加到 Promise 的回調函數之前執行。
另一方面,在使用 async/await 時, await 關鍵字會使 JavaScript 引擎暫停執行 async 函數,直到 Promise 解析或被拒絕。當 async 函數等待 Promise 解析時,它不會阻塞調用棧,因此可以執行任何其他同步代碼。一旦 Promise 解析完畢, async 函數將繼續執行,并返回 Promise 的結果。如果被拒絕,則會拋出一個錯誤值。