本文共 6061 字,大约阅读时间需要 20 分钟。
Async/await is a relatively new way to write asynchronous code in Javascript. Before we used and . Async/await actually builds on top of promises. If you have not used promises before, this is a good point to go brush up on them, find link to a useful article .
异步/等待是用Java编写异步代码的一种相对较新的方法。 在我们使用和之前。 异步/等待实际上建立在promise之上。 如果您以前没有使用过Promise,那么最好仔细阅读一下Promise,在找到指向有用文章的链接。
Why async/await
? Well, simply put, async/await allows us to write asynchronous code in a synchronous manner.
为什么要async/await
? 简而言之,异步/等待使我们能够以同步方式编写异步代码。
To create an async function all we need to do is add the async
keyword before the function definition, like this:
要创建异步函数,我们需要做的就是在函数定义之前添加async
关键字,如下所示:
async function asyncFunc() { return "Hey!";}
The one thing you need to know about async functions is that; they always returns a promise.
您需要了解的有关异步功能的一件事是: 他们总是兑现诺言 。
In the case where we explicitly return something that is not a promise, like above, the return value is automatically wrapped into a resolved promise with the resolved value being the non-promise. For the code above, asyncFunc().then(result => console.log(result))
will return the string Hey!
.
在像上面那样显式返回不是承诺的东西的情况下,返回值会自动包装到已解决的承诺中,而已解决的值是非承诺。 对于上面的代码, asyncFunc().then(result => console.log(result))
将返回字符串Hey!
。
The await
keyword can only be used within an async
block, otherwise it'll throw a syntax error. This means you cannot use await
in the top level of our code, basically, don't use it by itself.
await
关键字只能在async
块内使用 ,否则将引发语法错误。 这意味着您不能在我们的代码的顶层使用await
,基本上,请勿单独使用它。
When do we use it? If we have an asynchronous function inside of an async block. So let's say we need to fetch some data from our server and then use that data within our async block. We will use await
to pause the function execution and resume after the data comes in. For example;
我们什么时候使用它? 如果我们在异步块内有一个异步函数。 假设我们需要从服务器中获取一些数据,然后在异步块中使用这些数据。 我们将使用await
暂停函数执行,并在数据输入后继续执行。
async function asyncFunc() { // fetch data from a url endpoint const data = await axios.get("/some_url_endpoint"); return data;}
Why use await? Instead of using await we could have just used a promise right?
为什么要使用wait? 不用等待,我们可以只使用诺言吗?
async function asyncFunc() { let data; // fetch data from a url endpoint axios.get("/some_url_endpoint") .then((result) => { data = result }); return data;}
Await is simply a more elegant way to write a promise within an async function. It improves readability immensely and hence the reason we use it.
Await是在异步函数中编写Promise的一种更优雅的方法。 它极大地提高了可读性,因此提高了我们使用它的原因。
Let's assume we have a couple of asynchronous functions within our async
block. Instead of chaining promises we could do this, which is much cleaner:
假设我们在async
块中有几个异步函数。 不用链接承诺,我们可以这样做,这更加干净:
async function asyncFunc() { // fetch data from a url endpoint const response = await axios.get("/some_url_endpoint"); const data = await response.json(); return data;}
How do we handle errors? We have a few options, let's explore them:
我们如何处理错误? 我们有一些选择,让我们对其进行探讨:
This is the most common way to handle errors when using async-await
, good old try-catch
. All you need to do is encapsulate your code in a try
block and handle any errors that occur in a catch
.
这是使用async-await
和良好的try-catch
时处理错误的最常见方法。 您需要做的就是将代码封装在try
块中,并处理catch
中发生的所有错误。
async function asyncFunc() { try { // fetch data from a url endpoint const data = await axios.get("/some_url_endpoint"); return data; } catch(error) { console.log("error", error); // appropriately handle the error }}
If an error occurs when fetching data from our endpoint, execution is transferred to the catch
block and we can handle whatever error is thrown. If we have multiple await
lines the catch block catches the errors that occur in all the lines.
如果从端点获取数据时发生错误,执行将转移到catch
块,我们可以处理抛出的任何错误。 如果我们有多条await
线,catch块将捕获所有行中发生的错误。
async function asyncFunc() { try { // fetch data from a url endpoint const response = await axios.get("/some_url_endpoint"); const data = await response.json(); return data; } catch (error) { alert(error); // catches both errors }}
We can alternatively append .catch()
on the promise generated by the async
function. Let's recap: Remember that the async
function returns a promise. If an error occurs then it returns a rejected promise.So on the function call we could do this:
我们也可以在async
函数生成的.catch()
上附加.catch()
。 让我们来回顾一下:请记住, async
函数返回了一个Promise。 如果发生错误,则返回被拒绝的promise.So在函数调用中我们可以这样做:
asyncFunc().catch((error) => { // handle error appropriately});
Class methods can be async
.
类方法可以是async
。
class Example{ async asyncMethod() { const data = await axios.get("/some_url_endpoint"); return data }}
To call the method we'd do:
要调用该方法,我们将执行以下操作:
const exampleClass = new Example(); exampleClass.asyncMethod().then(//do whatever you want with the result)
We can append a .then()
on an await.
我们可以在等待中附加.then()
。
async function asyncFunc() { // fetch data from a url endpoint const data = await axios.get("/some_url_endpoint") .then((result) => return result.names) return data;}
If we have multiple promises we could use Promise.all
with await
.
如果我们有多个承诺,则可以将Promise.all
与await
Promise.all
使用。
async function asyncFunc() { const response = await Promise.all([ axios.get("/some_url_endpoint"), axios.get("/some_url_endpoint") ]); ...}
In summary, async/await
is a cleaner syntax to write asynchronous Javascript code. It enhances readability and flow of your code.
总而言之, async/await
是编写异步Javascript代码的更简洁的语法。 它增强了代码的可读性和流程。
Things to keep in mind while using async/await
:
使用async/await
时要记住的事情:
Its quite easy to learn and use. Enjoy experimenting!!
它非常容易学习和使用。 享受实验!
翻译自:
转载地址:http://isuwd.baihongyu.com/