AsyncAwait.vue 5.1 KB
Newer Older
hucy's avatar
hucy committed
1
<!-- eslint-disable @typescript-eslint/no-unused-vars -->
hucy's avatar
hucy committed
2 3 4 5 6 7 8 9 10 11 12
<!--
 * async await return
  -->
<script setup lang="ts">
import { onMounted, ref } from 'vue';

const primeNum = ref(1000000);
const msg = ref('');
const requestMsg = ref('');

onMounted(() => {
hucy's avatar
hucy committed
13
  fun1();
hucy's avatar
hucy committed
14 15 16 17
});
function getMag(name: any) {
  return `Hello, my name is ${name}.`;
}
hucy's avatar
hucy committed
18
function fun1() {
hucy's avatar
hucy committed
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
  const name = '张三';
  const msg = getMag(name);
  console.log(msg); // Hello, my name is 张三.
}

// 生成素数
function generatePrimes() {
  function isPrime(n: any) {
    // Math.sqrt() 函数返回一个数的平方根
    for (let c = 2; c <= Math.sqrt(n); ++c) {
      if (n % c === 0) {
        return false;
      }
    }
    return true;
  }

  let primes: number[] = [];
  const maximum = 1000000;
  while (primes.length < primeNum.value) {
    const candidate = Math.floor(Math.random() * (maximum + 1));
    if (isPrime(candidate)) {
      primes.push(candidate);
    }
  }
  msg.value = `已生成素数${primes.length}个`;
}

function xhrClick() {
  requestMsg.value = '';
  const xhr = new XMLHttpRequest();
  xhr.addEventListener('loadend', () => {
    requestMsg.value = `${requestMsg.value}完成!状态码:${xhr.status}`;
  });
  xhr.open(
    'GET',
    'https://raw.githubusercontent.com/mdn/content/main/files/en-us/_wikihistory.json'
  );
  xhr.send();
  requestMsg.value = '请求已发起\n';
}
function heavyLoad() {
  document.location.reload();
}

function fetchApi() {
hucy's avatar
hucy committed
65 66 67 68 69 70 71 72
  fn().then(
    function (data) {
      console.log('resolve回调', data);
      // console.log(somedata); // somedata未定义
    },
    function (error) {
      console.log('reject回调', error);
    }
hucy's avatar
hucy committed
73
  );
hucy's avatar
hucy committed
74
}
hucy's avatar
hucy committed
75

hucy's avatar
hucy committed
76 77 78 79 80 81 82 83 84 85 86 87
function fn() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      // Math.random 生成0~1的随机数
      // Math.ceil 向上取整
      let num = Math.ceil(Math.random() * 10); // 生成1~10的随机整数
      if (num <= 5) {
        resolve(`执行成功,num的值为:${num}`);
      } else {
        reject(`执行失败,该数字大于5,num的值为${num}`);
      }
    }, 1000);
hucy's avatar
hucy committed
88
  });
hucy's avatar
hucy committed
89
}
hucy's avatar
hucy committed
90

hucy's avatar
hucy committed
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
async function fetchProducts() {
  try {
    // 在这一行之后,我们的函数将等待 `fetch()` 调用完成
    // 调用 `fetch()` 将返回一个“响应”或抛出一个错误
    const response = await fetch(
      'https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json'
    );
    if (!response.ok) {
      throw new Error(`HTTP 请求错误:${response.status}`);
    } else {
      console.log(response);
    }
    // 在这一行之后,我们的函数将等待 `response.json()` 的调用完成
    // `response.json()` 调用将返回 JSON 对象或抛出一个错误
    const json = await response.json();
    console.log(json[0].name);
  } catch (error) {
    console.error(`无法获取产品列表:${error}`);
  }
hucy's avatar
hucy committed
110
}
hucy's avatar
hucy committed
111
// await fetchAPI示例
hucy's avatar
hucy committed
112 113 114 115
</script>
<template>
  <div class="fit">
    <div class="q-mb-md">async await return</div>
hucy's avatar
hucy committed
116 117 118 119 120 121 122
    <div class="q-mb-md">
      <a
        href="https://blog.csdn.net/huchaoyue_/article/details/127686795"
        target="_blank"
        >详细内容请查看CSDN</a
      >
    </div>
hucy's avatar
hucy committed
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
    <div class="content q-gutter-md">
      <q-card class="my-card bg-primary text-white">
        <q-card-section>
          <div class="q-mb-md q-gutter-sm">
            <q-btn
              color="white"
              text-color="primary"
              label="生成素数"
              @click="generatePrimes"
            />
          </div>
          <div>
            <q-input
              dark
              filled
              label-color="white"
              v-model="primeNum"
              label="素数个数"
            />
          </div>
          <div>{{ msg }}</div>
        </q-card-section>
      </q-card>

      <q-card class="my-card bg-orange-4 text-white">
        <q-card-section>
          <div class="q-mb-md q-gutter-sm">
            <q-btn
              color="white"
              text-color="orange-4"
              label="点击发起请求"
              @click="xhrClick"
            />
            <q-btn outline text-color="white" label="重载" @click="heavyLoad" />
          </div>
          <div>{{ requestMsg }}</div>
        </q-card-section>
      </q-card>

      <q-card class="my-card bg-purple-3 text-white">
        <q-card-section>
          <div class="q-mb-md q-gutter-sm">
            <q-btn
              no-caps
              color="white"
              text-color="purple-3"
              label="fetch API"
              @click="fetchApi"
            />
          </div>
        </q-card-section>
      </q-card>
hucy's avatar
hucy committed
175 176 177 178 179 180 181 182 183 184 185 186 187 188

      <q-card class="my-card bg-pink-3 text-white">
        <q-card-section>
          <div class="q-mb-md q-gutter-sm">
            <q-btn
              no-caps
              color="white"
              text-color="pink-3"
              label="async await"
              @click="fetchProducts"
            />
          </div>
        </q-card-section>
      </q-card>
hucy's avatar
hucy committed
189 190 191 192 193 194 195 196 197 198 199 200 201 202
    </div>
  </div>
</template>

<style lang="scss" scoped>
.content {
  display: flex;
  flex-flow: row wrap;
  align-items: flex-start;
}
.my-card {
  width: 300px;
}
</style>