avatar
fireworks99
keep hungry keep foolish

JS async/await

基于Promise的API,例如axios等,在使用时可以简化语法,方法是使用async/await组合。

await关键字只在 async 函数内有效。如果你在 async 函数体之外使用它,就会抛出语法错误 SyntaxError。

await 表达式会阻塞后续脚本的执行,直到其等待的基于 promise 的异步操作被兑现或被拒绝之后才会恢复进程。

Server

// Express提供了专门的路由方式
const express = require('express');

// 1.创建一个路由容器
const router = express.Router();

// 2.把路由都挂载到 router路由容器中
router.get('/async', (req, res) => {
  setTimeout(() => {
    res.send("Hello Async!");
  }, 2000);
})

// 3.导出路由
module.exports = router;

Client

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>

<body>
    <div id="app">
        <el-row>
            <el-button type="primary" @click="axiosBtn()">axios</el-button>
            <el-button type="success" round @click="asyncBtn()">async</el-button>
        </el-row>
    </div>

    <script>
        const app = new Vue({
            el: "#app",
            data() {
                return {}
            },
            methods: {
                axiosBtn() {
                    console.log("axiosBtn");

                    axios.get("http://localhost:3000/async")
                        .then(res => {
                            console.log(res);
                            if (res.status === 200) {
                                console.log(res.data);
                            }
                        });
                },
                async asyncBtn() {
                    console.log("asyncBtn");

                    let res = await axios.get("http://localhost:3000/async");
                    console.log(res);
                    if (res.status === 200) {
                        console.log(res.data);
                    }
                }
            }
        })
    </script>
</body>

</html>
Site by Baole Zhao | Powered by Hexo | theme PreciousJoy