onMounted中使用async改为同步

接口模拟

onMountedsetTimeout 模拟接口请求,默认为异步执行

<template>
----------
</template>

<script setup>
import { ref, reactive, onBeforeMount, onMounted } from "vue";
onMounted(() => {
  event3();
  event2(); 
  event4();
  event1();
});


const event1 = () => {
    setTimeout(() => {
      console.log("time1");
    }, 1000);
};

const event2 = () => {
  setTimeout(() => {
    console.log("time2");
  }, 2000);
};

const event3 = () => {
  setTimeout(() => {
    console.log("time3");
  }, 3000);
};

const event4 = () => {
    setTimeout(() => {
      console.log("time4");
    }, 4000);
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

执行结果

![await](https://img-blog.csdnimg.cn/d45e9d93e0b24cc2b73dd10928381b7c.png

使用 async 部分同步执行

onMounted( async () => {
  event3();
  event2();
 await event4();
 await event1(); 
});

const event1 = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
      console.log("event1");
    }, 1000);
  });
};

const event4 = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
      console.log("event4");
    }, 4000);
  });
};

执行结果

在这里插入图片描述

使用 async 全部同步执行

onBeforeMount(async () => {
  await event3(); //await
  await event2(); //await
  await event4(); //await
  await event1(); //await
});
const event1 = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
      console.log("event1");
    }, 1000);
  });
};

const event2 = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
      console.log("event2");
    }, 2000);
  });
};

const event3 = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
      console.log("event3");
    }, 3000);
  });
};

const event4 = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
      console.log("event4");
    }, 4000);
  });
};

执行结果

在这里插入图片描述

js单线程为什么支持异步执行

     JavaScript执行线程本身是单线程,但是整个浏览器不是单线程的。V8引擎在检测到异步调用,如setTimeout等WebAPIs调用后,会将其交给浏览器的其他线程进行执行处理,完了后再通过事件循环机制(event loop)返回执行线程执行回调。

事件循环和回调队列

在这里插入图片描述
tip:图片来源网络

     如图所示,浏览器V8引擎遇到同步任务会直接进入调用栈执行,遇到异步交给由浏览器的Web Apis来执行,执行完之后将回调添加到调用队列(任务队列),等调用栈的任务清空后执行调用队列事件,来实现 event loop。

codesandbox访问

在线沙盒

总结

  • async + await 改为同步
  • 方法必须 resolve 否则中下面断执行
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@才华有限公司

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值