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
效果一样