async/await的使用场景

async/await是基于promise的,promise主要是一个异步解决方案.

基于项目需求: 有10条数据,改了两条,这两条(控制机器开关命令)没有及时更新到数据库,需要保留这条和重新获取的十条(可 能没有更新)做个合并,这个合并就需要在重新获取之后,再重新渲染。

做了个demo: 基于mock,promise,async/await

下面是demo代码,粘贴可用。
实现功能: 点击或鼠标划入box时,重新获取数据之后合并数据
获取的数据(原始)格式
在这里插入图片描述

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

<head>
    <meta charset="UTF-8">
    <title>异步实际工作场景</title>
    <style>
        #box {
            width: 400px;
            height: 250px;
            background-color: rgb(243, 43, 43);
        }
    </style>
</head>

<body>
    <div id="box">111</div>
</body>
<script>
    const oBox = document.querySelector('#box');
    const url = 'https://easy-mock.com/mock/5d48e8d63dbe173654aeece4/api';
    const ss = {
        location: ["office01", "office02"],
        mode: 2,
        speed: 2,
        status: true,
        temp: 43,
    }
    var ajax = function (method, suffix) {
        return new Promise(function (resolve, reject) {
            const handler = function () {
                if (this.readyState !== 4) {//错误
                    return;
                } if (this.status === 200) {
                    resolve(this.response)
                } else {
                    reject(new Error(this.statusText))
                }
            }
            var xhr = new XMLHttpRequest();
            xhr.open(method, url + suffix);
            xhr.onreadystatechange = handler;
            xhr.responseType = 'json';
            xhr.setRequestHeader(
                'Content-Type', 'appllication/json'
            )
            xhr.send();
        })
    }

    var getSwitchs = function () {
        // debugger
        //promise:

        return new Promise(function (resolve, reject) {
            ajax('get', '/airSwitch')
                .then(res => {
                    console.log('get: ',res);
                    if (res.flag === 1) {
                        console.log(res.dateTime)
                        resolve(res.data)
                    }
                    else
                        reject(res.data.msg)
                })
                .catch(err => {
                    // reject(err)
                })
        })
    }
    //下面异步方法没有返回promise,所以不行
    var getSwitchs01 = async function () {
        let data;
        ajax('get', '/airSwitch')
            .then(res => {
                console.log('get: ',res);
                if (res.flag === 1) {
                    console.log(res.dateTime)
                    return  res.data;
                }
                else
                    return;
            })
            .catch(err => {
                // reject(err)
            })
    }
    // getSwitchs()

    var submit = function () {
        oBox.addEventListener('click', function () {
            getSwitchs()
                .then(value => {
                    console.log('执行完毕!!', ss, value.dateTime);
                    // debugger
                    dealData(ss, value);
                })
        })
        oBox.addEventListener('mouseenter', async function () {
            // const value = await getSwitchs();
            // console.log('value: ', value)
            dealData(ss, await getSwitchs())
            // dealData(ss, await getSwitchs())
        })
    }
    submit();

    function dealData(s, all) {
        let location = 0,
            dictionary = [
                ['制冷', '供热', '除湿', '新风'],
                ['高风', '中风', '低风']
            ]
        if (s.location.toString().indexOf('laboratory') !== -1) {
            location = 0;
        }
        else if (s.location.toString().indexOf('office') !== -1) {
            location = 1
        } else {
            location = 2
        }
        console.log(all)
        console.log(s)
        all[`area${location}`].forEach(item => {
            // debugger
            if (s.location.includes(item.sCode)){
                item = Object.assign(item, {
                    isOpen: s.status,
                    temperature: s.temp,
                    windVelocity: dictionary[0][s.speed],
                    energyMode: dictionary[1][s.mode]
                })
                console.log(item)
            } 
        })
        console.log('处理后: ', all)
    }
</script>

</html>

在这里插入图片描述

说明: 可以看到已经更改了,之所以一样forEach会改变原数组
几篇参考:
博客园(其中有vue中使用)
Async/Await替代Promise的6个理由

发布了15 篇原创文章 · 获赞 3 · 访问量 3441

猜你喜欢

转载自blog.csdn.net/qq_39370934/article/details/99981592