函数中使用了axios,返回值return为空的解决方法

1.问题出现

在Vue3的项目中,需要使用axios来获取数据,于是想要自己封装一个函数,函数中使用axios去请求数据,请求得的数据作为函数的返回值去return。思路简单,写法如下:
下面为发送请求的函数 postCluster

export const postCluster = (ods: string[]): string[] => {
  // 向后端发起请求
  let result: string[] = [];
  axios
    .post(
      "http://127.0.0.1:5000/cluster",
      { ods: JSON.parse(JSON.stringify(ods)) },
      {
        headers: {
          "Content-Type": "application/json",
        },
      }
    )
    .then(function (response) {
      // 处理成功情况
      console.log(response.data);
      result = response.data;
    })
    .catch(function (error) {
      // 处理错误情况
      console.log(error);
    })
    .finally(function () {
      // 总是会执行
    });
  return result;
};

App.vue中调用函数postCluster

<script setup lang="ts">
import { useDirectionStore } from "./stores/directionStore";
import { onMounted } from "vue";
import { postCluster } from "@/utils/myaxios";
const directionStore = useDirectionStore();

const testConnect = () => {
  const ods = directionStore.Ods;
  const res = postCluster(ods["bicyclingOds"]);
  console.log(res);
};

onMounted(async () => {
  await directionStore.fetchData();
  await directionStore.weightMode([1, 1, 1, 1]);
});
</script>

<template>
  <div>
    <button @click="testConnect">打印</button>
  </div>
</template>

<style scoped></style>
@/utils/myaxios

结果就是函数中的返回值为空,但是axios的then中却有数据
问题

2.问题分析

这个现象是因为axios.post是一个异步操作,它会在后台发送请求并等待响应,而不会阻塞代码的执行。因此,在axios.post方法执行时,JavaScript引擎会继续执行后面的代码,包括return result语句。

由于axios.post是异步的,它会在后台发送请求,而不会等待服务器的响应返回。因此,在return result语句执行时,result的值仍然是初始值[],因为异步操作尚未完成,响应数据尚未被赋值给result。

而在console.log(response.data)语句中,response.data的打印是在异步操作axios.post的.then回调函数中执行的。在该回调函数中,response.data已经被正确赋值给了result,因此可以正确地打印出数据。

3.解决办法

使用异步的方式来获取postCluster函数的结果,例如使用Promise、async/await或回调函数等。在使用Promise或async/await的情况下,函数调用方需要以异步的方式来处理postCluster函数的返回值,以确保在异步操作完成后获取到正确的结果。

以下使用Promise来处理异步操作。通过返回一个Promise对象,在异步操作完成后通过async/await或者.then方法来解析Promise对象以获取最终的结果。例如我这里函数返回值是Promise<string[]>类型的,就需要从Promise<string[]>类型的对象中获取string[]类型的数据。

3.1 第一步:修改函数返回值为Promise对象

使用async/await可以返回一个Promise对象

export const postCluster = async (ods: string[]): Promise<string[]> => {
  let result: string[] = [];
  await axios
    .post(
      "http://127.0.0.1:5000/cluster",
      { ods: JSON.parse(JSON.stringify(ods)) },
      {
        headers: {
          "Content-Type": "application/json",
        },
      }
    )
    .then(function (response) {
      // 处理成功情况
      console.log(response.data);
      result = response.data;
    })
    .catch(function (error) {
      // 处理错误情况
      console.log(error);
    })
    .finally(function () {
      // 总是会执行
    });
  return result;
};

或者直接new一个

export const postCluster = (ods: string[]): Promise<string[]> => {
  return new Promise((resolve, reject) => {
    axios
      .post(
        "http://127.0.0.1:5000/cluster",
        { ods: JSON.parse(JSON.stringify(ods)) },
        {
          headers: {
            "Content-Type": "application/json",
          },
        }
      )
      .then(function (response) {
        // 处理成功情况
        console.log(response.data);
        resolve(response.data);
      })
      .catch(function (error) {
        // 处理错误情况
        console.log(error);
        reject(error);
      })
      .finally(function () {});
  });
};

3.2 第二步:从Promise对象解析出数据

修改App.vue中调用函数postCluster的方式为async/await,从函数返回值解析出数据

<script setup lang="ts">
import { useDirectionStore } from "./stores/directionStore";
import { onMounted } from "vue";
import { postCluster } from "@/utils/myaxios";
const directionStore = useDirectionStore();

const testConnect = async () => {
  const ods = directionStore.Ods;
  const res = await postCluster(ods["bicyclingOds"]);//加了await返回值就变为string[]类型的,不加是Promise<string[]>类型的
  console.log(res);
};

onMounted(async () => {
  await directionStore.fetchData();
  await directionStore.weightMode([1, 1, 1, 1]);
});
</script>

<template>
  <div>
    <button @click="testConnect">打印</button>
  </div>
</template>

<style scoped></style>
@/utils/myaxios

函数返回值成功得到数据
在这里插入图片描述
也可以对Promise对象使用.then

<script setup lang="ts">
import { useDirectionStore } from "./stores/directionStore";
import { onMounted } from "vue";
import { postCluster } from "@/utils/myaxios";
const directionStore = useDirectionStore();

const testConnect = () => {
  const ods = directionStore.Ods;
  const promiseObj = postCluster(ods["bicyclingOds"]); // postCluster函数返回的是Promise<string[]>
  promiseObj
    .then((data) => {
      // 在这里处理获取到的string[]数据
      console.log(data);
    })
    .catch((error) => {
      // 处理错误情况
      console.log(error);
    });
};
onMounted(async () => {
  await directionStore.fetchData();
  await directionStore.weightMode([1, 1, 1, 1]);
});
</script>

<template>
  <div>
    <button @click="testConnect">打印</button>
  </div>
</template>

<style scoped></style>
@/utils/myaxios

效果一样
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

诸法空如

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

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

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

打赏作者

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

抵扣说明:

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

余额充值