【发布时间】:2021-05-06 19:39:02
【问题描述】:
我想以 Promise 风格的方式发出 Axios 请求。 Axios 请求在“dataLayer.js”中完成。 问题是我的“dataPromise”已经满了。 如何在数据层类中扩展“createChargingStations()”以进行类似 Promise 的调用,以便可以使用“.then()”处理 SFC 中的数据,如下所示?
非常感谢!
// dataLayer.js
export class modelFactory {
chargingStationsArray = []
createChargingStations() {
const requestPromise = axios.request(/* some request config */)
const dataPromise = requestPromise.then(response => {
response.data.forEach(dataEntry => {
let cs = new chargingStation()
/* some data mapping and transformation here */
/* ... */
// after tranformation, finally push chargingStation object
this.chargingStationsArray.push(cs)
})
}).catch(error => {
console.log("Promise Rejected: " + error);
})
}
}
// SFC.vue
<template> <!-- some template --> </template>
<script>
export default {
/* name, components, data() etc. */
methods: {
updateMapOnFilterChange() {
var mf = new modelFactory()
const promise = mf.createChargingStations()
promise.then(chargingStationsArray => {
/* inject array into Vue component property */
}).catch(error => {
console.log("Promise Rejected: " + error);
})
}
}
}
</script>
编辑:在这里发布了代码的长版本https://jsfiddle.net/3azdnc4j/ 您可能会更好地掌握代码应该做什么。但在我看来,基本问题没有必要!
【问题讨论】:
-
不知道你已经改变了什么。您可以只链接承诺,并且不要忘记在函数中返回它。有时这是一个艰难的概念。
-
您的代码不应该按原样工作,
promise.then()应该抛出。请创建一个minimal reproducible example 像codesanbox -
不确定,你想实现什么,你想访问你的 vue 文件中的
chargingStationsArray数据吗? -
@Naren: 是的,我想在 vue 组件中访问完整的chargingStationsArray,然后请求就完成了
-
@TJ:我试过了,但是 babel 转译和正确的 vue 版本有问题。所以我决定以一种抽象和孤立的方式提出我的问题,因为这更像是一个概念问题。
标签: javascript vue.js axios es6-promise