博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用Async的异步Javascript-等待
阅读量:2508 次
发布时间:2019-05-11

本文共 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:

我们如何处理错误? 我们有一些选择,让我们对其进行探讨:

试着抓 (Try..catch)

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 }}

如果不尝试..catch (If not try..catch)

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});

( )

在类方法上异步 (Async on class methods)

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)

然后等待 (Await is thenable)

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;}

等待<> Promise.all (Await <> Promise.all)

If we have multiple promises we could use Promise.all with await.

如果我们有多个承诺,则可以将Promise.allawait 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时要记住的事情:

  • Async functions return a promise.

    异步函数返回一个Promise。
  • Await can only be used inside an async block.

    等待只能在异步块内使用。
  • Await waits until the function("promise") resolves or rejects.

    等待等待,直到函数(“承诺”)解决或拒绝为止。

Its quite easy to learn and use. Enjoy experimenting!!

它非常容易学习和使用。 享受实验!

翻译自:

转载地址:http://isuwd.baihongyu.com/

你可能感兴趣的文章
进程和线程概念及原理
查看>>
Lucene、ES好文章
查看>>
android 生命周期
查看>>
jquery--this
查看>>
MySQL 5.1参考手册
查看>>
TensorFlow安装流程(GPU加速)
查看>>
OpenStack的容器服务体验
查看>>
【BZOJ 4059】 (分治暴力|扫描线+线段树)
查看>>
BZOJ 1066 蜥蜴(网络流)
查看>>
提高批量插入数据的方法
查看>>
Linux重启Mysql命令
查看>>
前端模块化:RequireJS(转)
查看>>
应用程序缓存的应用(摘抄)
查看>>
jQuery基础知识,很赞的!!!
查看>>
JK_Rush关于索引的一些总结
查看>>
[Codevs] 线段树练习5
查看>>
Amazon
查看>>
component-based scene model
查看>>
Echart输出图形
查看>>
hMailServer搭建简单邮件系统
查看>>