es7 的 await, async function

本文深入探讨ES7中async/await的使用方法及其在异步编程中的优势。通过具体案例,展示了如何利用async函数简化Promise操作,以及await关键字如何等待Promise完成。适合希望提升JavaScript异步编程技能的开发者阅读。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值