无法从Axios发出的请求中获取我的数据。我的控制台日志打印正确,但是当我尝试将其设置为变量或返回变量时,我什么也没得到。
static getGroupByID(groupID) {
var self = this;
var group = '';
axios.post((GRAPHQL_END_POINT), {
query: print(Queries.GET_GROUP_BY_ID),
variables: {
groupID: groupID
}`enter code here`
})
.then(res => {
console.log(res.data.data.getGroup.name);
self.group = res.data.data.getGroup.name;
})
.catch(err => console.log(err))
return group;
}
答案 0 :(得分:0)
static getGroupByID(groupID) {
var self = this;
var group = '';
return axios.post((GRAPHQL_END_POINT), { <-- Return your promise
query: print(Queries.GET_GROUP_BY_ID),
variables: {
groupID: groupID
}`enter code here`
})
.then(res => {
console.log(res.data.data.getGroup.name);
return res.data.data.getGroup.name; <--- Return your data and use getGroupById(...).then(...)
})
.catch(err => console.log(err))
}
答案 1 :(得分:0)
查询是异步的,您的函数返回空的group = ''
,将值设置为state或使用await。该函数在查询完成之前返回,您可以使用async / await使查询完成。
static async getGroupByID(groupID) {
try {
const res = await axios.post(GRAPHQL_END_POINT, {
query: print(Queries.GET_GROUP_BY_ID),
variables: {
groupID: groupID
}
});
const { data } = await res;
return data;
} catch (error) {
console.log(error);
}
}
或者您可以只返回诺言并在调用函数的地方进行处理。
static getGroupByID(groupID) {
return axios.post(GRAPHQL_END_POINT, {
query: print(Queries.GET_GROUP_BY_ID),
variables: {
groupID: groupID
}
});
}