🎈详解同步和异步

111 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第7天,点击查看活动详情

🎈大家好,我是橙橙子,新人初来乍到,请多多关照~

📝小小的前端一枚,分享一些日常的学习和项目实战总结~

😜如果本文对你有帮助的话,帮忙点点赞呀!ღ( ´・ᴗ・` )比心~

JS 是一门单线程的编程语言,这就意味着一个时间里只能处理一件事,也就是说JS引擎一次只能在一个线程里处理一条语句。 使用异步 (如 回调函数、promiseasync/await),可以不用阻塞主线程的情况下长时间执行网络请求。 什么是执行上下文调用栈(也称为执行堆栈)。

函数代码在函数执行上下文中执行,全局代码在全局执行上下文中执行。每个函数都有自己的执行上下文。

调用栈

调用堆栈顾名思义是一个具有LIFO(后进先出)结构的堆栈,用于存储在代码执行期间创建的所有执行上下文。

  • await 只能在 async 标记的函数内部使用,单独使用会触发 Syntax error。

  • await后面需要跟异步操作,不然就没有意义,而且await后面的Promise对象不必写then,因为await的作用之一就是获取后面Promise对象成功状态传递出来的参数。

  • for循环遍历数组

  • for...in遍历对象

  • for...of遍历类数组对象(ES6)

  • Object.keys()获取对象属性名的集合

防止无意识重复点击按钮

给按钮添加控制,在control 毫秒内,第一次点击事件之后的点击事件不执行
💡举个栗子:

    <template>
    <button @click="handleClick"></button>
        </templage>
        <script>
    export default {
        methods: {
            handleClick(event) {
                if (this.disabled) return;
                if (this.notAllowed) return;
                // 点击完多少秒不能继续点
                this.notAllowed = true;
                setTimeout(()=>{
                    this.notAllowed = false;
                }, this.control)
                this.$emit('click', event, this);
            }
        }
    }
</script>

按钮点击立马禁用,等响应回来才能继续点击

触发点击的button实例传入fetch配置,代码如下:
💡举个栗子:


doQuery: function (button) {
    this.FesApi.fetch(`generalcard/query`, {
        sub_card_type: this.query.sub_card_type,
        code_type: this.query.code_type,
        title: this.query.title,
        card_id: this.query.card_id,
        page_info: {
            pageSize: this.paginationOption.page_info.pageSize,
            currentPage: this.paginationOption.page_info.currentPage
        }
    }, {
        //看这里,加上下面一行代码就行。。so easy
        button: button
    }).then(rst => {
        // 成功处理
    });
}

在fetch函数内部,设置button的disabled=true,当响应回来时,设置disabled=false代码如下:
💡举个栗子:

const action = function (url, data, option) {
    // 如果传了button
    if (option.button) {
        option.button.currentDisabled = true;
    }
    // 记录日志
    const log = requsetLog.creatLog(url, data);

    return param(url, data, option)
        .then(success, fail)
        .then((response) => {
            requsetLog.changeLogStatus(log, 'success');
            if (option && option.button) {
                option.button.currentDisabled = false;
            }
            return response;
        })
        .catch((error) => {
            requsetLog.changeLogStatus(log, 'fail');
            if (option && option.button) {
                option.button.currentDisabled = false;
            }
            error.message && window.Toast.error(error.message);
            throw error;
        });
};