與 Promise 相比,async/await 是一種更新的非同步程式碼編寫方式。 async/await 的主要優點是提高了可讀性並避免了承諾鏈。 Promise 可能會變得很長、難以閱讀,並且可能包含難以調試的深層嵌套回呼。
回想一下我們之前的獲取。
fetch('https://jsonplaceholder.typicode.com/todos/1') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)) .finally(() => console.log('All done'));
使用 async/await,程式碼可以重構為如下所示:
async function fetchData() { try { const response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); const data = await response.json(); console.log(data); } catch (error) { console.error('Error:', error); } finally { console.log('All done'); } } fetchData();
雖然可能多了幾行程式碼,但這個版本更容易閱讀,因為它類似於普通的同步函數。此外,如果 .then() 語句內的函數更複雜,則可讀性和可調試性將受到更大的影響。 async/await 範例更加清晰。
async/await 函數有兩個基本部分:async 和await。 async 關鍵字加在函數宣告前,await 用於非同步任務開始時。
讓我們以從餐廳點餐的例子來說明這一點:
// Simulate the order process with async/await async function foodOrder() { console.log("Ordering food..."); await new Promise(resolve => setTimeout(resolve, 2000)); // Wait 2 seconds for food to be prepared return "Your food is ready!"; } // Simulate the eating process function eatFood(order) { console.log(order); // This logs "Your food is ready!" console.log("Enjoying the meal!"); } // Simulate continuing the conversation function continueConversation() { console.log("While waiting, you continue chatting with friends..."); } async function orderFood() { console.log("You've arrived at the restaurant."); const order = await foodOrder(); // Place the order and wait for it to be ready continueConversation(); // Chat while waiting eatFood(order); // Eat the food once it arrives } orderFood();
輸出將是
You've arrived at the restaurant. Ordering food... While waiting, you continue chatting with friends... Your food is ready! Enjoying the meal!
以上是異步/等待的詳細內容。更多資訊請關注PHP中文網其他相關文章!