如何用實例掌握Async/Await

今天讓我們一起來探討如何用實例掌握Async/Await
在這裏插入圖片描述目錄
1、簡介(callbacks, promises, async/await)

2、實例—貨幣轉換器從2個API’s接收異步數據。

簡介
Async/await是一種編寫異步代碼的新方法。它是建立在promises之上的,所以也是非阻塞。
最大的差別在於異步代碼看起來更靠近同步代碼。這就是它的關鍵所在。
以前的異步代碼選項是callbacks and promises。

回調函數程序

setTimeout(() => {
  console.log('This runs after 1000 milliseconds.');
}, 1000);

回調的問題——臭名昭著的回調地獄
在回調函數中嵌套回調函數很快就會變成這樣:
在這裏插入圖片描述
回調地獄
回調被嵌套在其他回調的幾層的情況,可能使代碼難以理解和維護。

Promises程序

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來創建的,如下所示:

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看起來類似於同步代碼,而且同步代碼更容易理解。現在我們已經介紹了基本知識,讓我們繼續看真實世界中的例子!

貨幣轉換器
項目說明和設置

在本教程中,我們將構建一個簡單但有教育意義、有用的應用程序,它將提高您對Async/ wait的整體認識。
這個程序將體現我們想要從某種貨幣代碼轉換爲另一種貨幣代碼以及金額。然後,程序將根據來自api的數據輸出正確的匯率。

在這個應用程序中,我們將從兩個異步源接收數據:
1、貨幣層—— https://currencylayer.com—您需要免費註冊,這樣才能使用API訪問密鑰。這個API將爲我們提供計算貨幣間匯率所需的數據。
2、其他國家— http://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);
  });

你將收到的輸出:
image.png

今天的分享就到這裏,希望本文能幫助到您!

點贊,讓更多的人也能看到這篇內容(收藏不點贊,都是耍流氓 -_-)
關注公衆號「新前端社區」,享受文章首發體驗!
每週重點攻克一個前端技術難點。
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章