es7 的 await, async function

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/palmer_kai/article/details/82912419

es7 的 await, async function

简单概念

await:

The await operator is used to wait for a Promise. It can only be used inside an async function.

async:

The async function declaration defines an asynchronous function, which returns an AsyncFunction object. An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result. But the syntax and structure of your code using async functions is much more like using standard synchronous functions.

上面是 mdn 对两个概念的释义, 简单理解就是:

await 用来等待一个 promise 实例, 只能用在 async function 对应的函数中。

async function 用来定义一个异步函数。

浏览器来说异步一般就是 1. 定时器; 2. 网络请求 3. dom, bom 事件,并且异步的执行都是 通过事件队列进行的

案例

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>await</title>
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> 
</head>

<body>
  <script>
    // await 存在的意义可能是 为了 封装 Promise 对象
    function resolveAfter2Seconds(x) { // 异步事件, ajax 请求
      return new Promise((res, rej) => {
        setTimeout(() => {
          if (x) {
            x *= x;
            res(x);
          } else {
            // rej('real params required!');
            rej();
          }
          
        },2000)
      } );
    }

    async function f1 (x) {
      let y = await resolveAfter2Seconds(x);

      // 获取数据后要做的事情
      console.log(`y ---- ${y}`);
    }


    async function f2 () {
      var y = await 20;
      console.log(y);
    }

   async function f3(x) {
      let y = await resolveAfter2Seconds(x)
              .catch(err => console.log(err));
      // 异步结束后要做的事情
      // 如果 y 存在说明 success , y 为 undefined 则 表明 失败了
      console.log(`y ---- ${y}`);
    }
  </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/palmer_kai/article/details/82912419