说明: 我翻译本身读过的文章,仅仅只是我做为一个新手的一种学习方式。不少专业化的表达可能不是很是准确!文章中或许有翻译错误的地方,若是你看到了,但愿能够在评论中指出,我会及时修正。对于大佬的你请直接忽视跳过,一样是小白的你,能够考虑看看。固然若是有能力,我强烈建议你直接看原文前端
在写这篇文章的同时,我还录制了一个相关的视频,已上传到 Youtube。 你能够边看视频边敲代码,我建议你先看下视频,而后再以这篇文章为引导本身练习下代码。ios
视频地址:Learn Async/Await in This Real World Projectgit
Async/Await 是一种创建在 promises 基础上的,书写异步代码的新方式,因此它也是非阻塞的。github
与咱们以前异步编程所使用到的回调函数和 promises 相比较,最大的区别就是 async/await 使咱们的异步代码看起来就像同步代码同样,这也正是它的厉害之处。npm
setTimeout(() => {
console.log('This runs after 1000 milliseconds.');
}, 1000);
复制代码
在回调函数中嵌套回调函数,看起来就像这样:编程
指的是回调函数被嵌套在另外一个回调函数中,嵌套层级有多层,使咱们的代码可读性和可维护性变得很是差。axios
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);
});
复制代码
promiseFunction 这个函数返回一个表示函数运行过程的 Promise 对象, resolve 函数表示任务已经完成。api
而后,咱们就能够在 promiseFunction 函数的基础上调用 then()
和 catch()
方法。数组
then: Promise 成功后执行的回调函数。
catch: 当遇到了错误后执行的回调函数。promise
Async函数为咱们提供了简洁的语法,咱们能够经过它实现与 Promise 相同的效果,可是代码量会减小不少。其实底层原理上,async 不过是 promises 的语法糖而已。
在普通的函数声明前加上 async 关键字,咱们就建立了一个 async 函数:
const asyncFunction = async () => {
// Code
}
复制代码
异步函数使用 await 表达式能够暂停函数的执行,await 关键字只能在 async 函数中使用,它会返回 Promise 对象的处理结果。
promises 和 async/await 的区别:
// 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/Await 更易于咱们理解,由于它看起来像同步代码。
前面咱们已经介绍过这些基础知识了,如今咱们来看看在现实开发中怎么使用!
在下面的教程中,咱们将建立一个简单实用,并且颇有学习意义的应用程序,相信会加深你对 Async/Await 理解
咱们将原始货币代码和想要获得的货币代码,以及金额输入程序,而后程序会调用相关的 API,最后将正确的汇率显示出来
在这个程序中,咱们将从如下两个 API 异步获取数据:
首先,建立一个新目录并运行 npm init
初始化项目,接下里咱们选择默认值,跳过全部步骤,而后再输入 npm i——save axios
安装 axios。在当前文件夹内建立一个 currency-convert .js
的文件。
在 currency-convert .js
文件中,咱们先经过 require
语法引入 axios
const axios = require(‘axios’);` 复制代码
这个程序中,咱们须要三个异步函数,第一个函数用来获取关于货币的数据;第二个函数用来获取关于国家的数据;第三个函数用来将全部信息集中起来并展现给用户看
咱们建立一个接收两个参数(fromCurrency 和 toCurrency)的异步函数。
const getExchangeRate = async (fromCurrency, toCurrency) => {}
复制代码
如今咱们获取数据,而后经过使用 async/await,能够直接将咱们想要的数据赋值给变量。调用接口以前别忘了要注册帐号,才能得到 API access key
const getExchangeRate = async (fromCurrency, toCurrency) => {
const response = await axios.get('http://data.fixer.io/api/latest? access_key=[yourAccessKey]&format=1');
}
复制代码
咱们能够经过 response.data.rates
来提取咱们想要的数据,而后咱们将它赋值给一个变量 rate
:
const rate = response.data.rates;
复制代码
由于全部的数据都是从欧元转换过来的,咱们能够建立一个变量 euro
,它的值等于:
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}`);
复制代码
而后经过数组 map 方法将 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 语句捕捉:
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);
});
复制代码
你会看到下面的结果:
很不错,你坚持到了最后!若是在学习过程当中遇到了困惑的地方,你能够参考这个仓库里的代码。若是你有任何问题,能够在下面留言。你也可关注个人 Youtube 专栏,我会带来更多干货给你们!