javascript - 在 Axios 请求中使用 Promise
问题描述
我正在努力找出实现某事的最佳方法。当我登陆个人资料页面时,个人资料组件会加载该个人资料的数据。这是分配给this.profile
. 在这个数据中是一个文件的路径,我想使用这个文件处理一些数据。对我来说,下面的方法似乎有点冒险。
created() {
let vm = this;
let url = `/api/profile/${this.$route.params.id}`;
axios.get(url).then(response => {
this.profile = response.data;
d3.json(response.data.fileName)
.then(function (data) {
//do some stuff
}).catch(function (error) {
// handle error
});
});
}
相反,我想确保我首先拥有来自 axios 调用的数据。所以我想我需要一个承诺?我在想更多的事情
created() {
let vm = this;
let url = `/api/profile/${this.$route.params.id}`;
axios.get(url).then(response => {
this.profile = response.data;
}).then() {
d3.json(response.data.fileName)
.then(function (data) {
//do some stuff
}).catch(function (error) {
// handle error
});
};
}
但以上是不正确的,主要是为了展示我想要实现的目标。我想知道如何才能使用 deferred 并承诺在 axios 调用后仅执行 d3 的东西。
谢谢
解决方案
这就是async/await
派上用场的地方。A 你不需要保存this
到变量中,B 你有更干净、更易读的代码。
async created() {
const url = `/api/profile/${this.$route.params.id}`;
const { data } = await axios.get(url); // Optional destructuring for less clutter
this.profile = data;
const d3Data = await d3.json(data.fileName);
//do whatever you want
}
推荐阅读
- c - 如何读入文件,然后将文件中的每个结构放入数组中?
- reactjs - 反应选择不适用于反应传单弹出
- java - 创建数据矩阵时如何使用 pantone 代码?
- cmd - 如何将新创建的文件从多个目录复制到单个目录 uisng ssis 或 cmd?
- java - java - 如何在java中获取字符串格式时间“2019-01-25 14:34:34.123456789”的纪元以来的纳秒?
- c# - KeyValue 列表使用哪种数据结构
- symfony - 在 Syfmony PHPUnit 测试中模拟两个 ObjectRepositories
- python - 无法使用漂亮的搜素从 Python 中的网页中提取图像
- php - 将长字符串分配给变量和随后将较小的字符串附加到变量之间在性能上有什么区别吗?
- windows - Golang os.Rename(
, ) 在 Windows 中不起作用