今天讓咱們一塊兒來探討如何用實例掌握Async/Await前端
目錄
一、簡介(callbacks, promises, async/await)
二、實例—貨幣轉換器從2個API’s接收異步數據。ios
簡介
Async/await是一種編寫異步代碼的新方法。它是創建在promises之上的,因此也是非阻塞。 最大的差異在於異步代碼看起來更靠近同步代碼。這就是它的關鍵所在。 之前的異步代碼選項是callbacks and promises。npm
回調函數程序axios
setTimeout(() => {
console.log('This runs after 1000 milliseconds.');
}, 1000);
複製代碼
回調的問題——臭名昭著的回調地獄
在回調函數中嵌套回調函數很快就會變成這樣:api
Promises程序promise
const promiseFunction = new Promise((resolve, reject) => {
const add = (a, b) => a + b;
resolve(add(2, 2));
});
promiseFunction.then((response) => {
console.log(response);
}).catch((error) => {
console.log(error);
});
複製代碼
Promise函數返回一個Promise,該Promise表示函數的進程。resolve函數向Promise實例發出它已經完成的信號。 而後,咱們能夠調用promise函數的then()和.catch(): then —在 promise完成後運行傳遞給它的回調。 catch —運行一個回調,當發生錯誤時傳遞給它。異步
異步函數
Async函數爲咱們提供了一個乾淨簡潔的語法,使咱們可以編寫更少的代碼來實現與promises相同的結果。Async只不過是promises的語法糖。Async函數是經過在函數聲明以前加上Async來建立的,以下所示:async
const asyncFunction = async () => {
// Code
}
複製代碼
異步函數能夠用await暫停,await是隻能在異步函數中使用的關鍵字。await返回異步函數完成後返回的任何內容。 這是promises和async/ wait之間的區別:函數
// Async/Await
const asyncGreeting = async () => 'Greetings';
// Promises
const promiseGreeting = () => new Promise(((resolve) => {
resolve('Greetings');
}));
asyncGreeting().then(result => console.log(result));
promiseGreeting().then(result => console.log(result));
複製代碼
Async/ wait看起來相似於同步代碼,並且同步代碼更容易理解。如今咱們已經介紹了基本知識,讓咱們繼續看真實世界中的例子!spa
貨幣轉換器
項目說明和設置
在本教程中,咱們將構建一個簡單但有教育意義、有用的應用程序,它將提升您對Async/ wait的總體認識。 這個程序將體現咱們想要從某種貨幣代碼轉換爲另外一種貨幣代碼以及金額。而後,程序將根據來自api的數據輸出正確的匯率。
在這個應用程序中,咱們將從兩個異步源接收數據:
一、貨幣層—— currencylayer.com—您須要免費註冊,這樣才能使用API訪問密鑰。這個API將爲咱們提供計算貨幣間匯率所需的數據。
二、其餘國家— restcountries.eu/—這個API會告訴咱們…
首先,建立一個新目錄並運行 npm init,跳過全部步驟,而後經過鍵入npm i --save axios.安裝axios。新建一個文件夾命名爲currency-converter.js.。
讓咱們深刻研究async/await 咱們這個程序的目標是有三個函數。不是一個,不是兩個,而是三個異步函數。第一個函數是獲取關於貨幣的數據。第二個函數是獲取關於國家的數據。第三個函數將把信息收集到一個地方並很好地輸出給用戶。
第一個函數—異步接收貨幣數據
咱們將建立一個異步函數,它將接收fromCurrency和toCurrency兩個參數。
const getExchangeRate = async (fromCurrency, toCurrency) => {}
複製代碼
如今咱們須要獲取數據。使用async/ wait,咱們能夠直接將數據分配給一個變量;不要忘記註冊並輸入您本身正確的訪問密鑰。
const getExchangeRate = async (fromCurrency, toCurrency) => {
const response = await axios.get('http://data.fixer.io/api/latest? access_key=[yourAccessKey]&format=1');
}
複製代碼
響應中的數據在response.data.rates下可用,因此咱們能夠把它放到響應下面的變量中:
const rate = response.data.rates;
複製代碼
由於全部的東西都是從歐元轉換而來的,下面,咱們將建立一個名爲歐元的變量,它將等於1/咱們想要轉換的貨幣:
const euro = 1 / rate[fromCurrency];
複製代碼
爲了獲得一個匯率,咱們能夠用歐元乘以咱們想要轉換成的貨幣:
const exchangeRate = euro * rate[toCurrency];
複製代碼
最後,函數應該是這樣的:
第二個函數—異步接收國家數據
咱們將建立一個異步函數,它將使用currencyCode做爲參數
const getCountries = async (currencyCode) => {}
複製代碼
如前所述,咱們將獲取數據並將其分配給一個變量:
const response = await axios.get(`https://restcountries.eu/rest/v2/currency/${currencyCode}`);
複製代碼
而後,咱們將映射數據並返回 country.name:
return response.data.map(country => country.name);
複製代碼
最後,函數應該是這樣的:
咱們將建立一個異步函數,它將取fromCurrency、toCurrency和 amount做爲參數:
const convert = async (fromCurrency, toCurrency, amount) => {}
複製代碼
首先,咱們獲得貨幣數據:
const exchangeRate = await getExchangeRate(fromCurrency, toCurrency);
複製代碼
其次,咱們獲得國家的數據:
const countries = await getCountries(toCurrency);
複製代碼
第三,將轉換後的金額保存爲一個變量:
const convertedAmount = (amount * exchangeRate).toFixed(2);
複製代碼
最後,咱們把它所有輸出給用戶:
return `${amount} ${fromCurrency} is worth ${convertedAmount} ${toCurrency}. You can spend these in the following countries: ${countries}`;
複製代碼
全部這些最後應該是這樣的:
添加try/catch來處理錯誤狀況
咱們須要把全部的邏輯封裝在 try中,若是有錯誤,就捕捉錯誤:
const getExchangeRate = async (fromCurrency, toCurrency) => {
try {
const response = await axios.get('http://data.fixer.io/api/latest?access_key=f68b13604ac8e570a00f7d8fe7f25e1b&format=1');
const rate = response.data.rates;
const euro = 1 / rate[fromCurrency];
const exchangeRate = euro * rate[toCurrency];
return exchangeRate;
} catch (error) {
throw new Error(`Unable to get currency ${fromCurrency} and ${toCurrency}`);
}
};
複製代碼
對第二個函數重複一樣的操做:
const getCountries = async (currencyCode) => {
try {
const response = await axios.get(`https://restcountries.eu/rest/v2/currency/${currencyCode}`);
return response.data.map(country => country.name);
} catch (error) {
throw new Error(`Unable to get countries that use ${currencyCode}`);
}
};
複製代碼
因爲第三個函數只處理第一個和第二個函數提供的內容,所以不須要檢查錯誤。 最後,咱們能夠調用函數並接收數據:
convertCurrency('USD', 'HRK', 20)
.then((message) => {
console.log(message);
}).catch((error) => {
console.log(error.message);
});
複製代碼
你將收到的輸出:
今天的分享就到這裏,但願本文能幫助到您!
點贊,讓更多的人也能看到這篇內容(收藏不點贊,都是耍流氓 -_-)
關注公衆號「新前端社區」,享受文章首發體驗!
每週重點攻克一個前端技術難點。