[英]Is there a difference in data/promise returned from axios get and post?
[英]Make axios call from another axios promise and save returned data
我正在从另一个axios
调用的 promise 进行 axios 调用,代码如下所示,调用基本上是从第一种方法到第二种方法。
基于建议的更新代码它只是说:不能在异步function之外使用关键字'await'然后我尝试了
var data = async () => {
await this.checkParentLoggerLevel();
};
仍然没有工作
async updateLevel(logger, level, index) {
alert(index);
axios
.post(
'url'
)
.then(() => {
var data = await this.checkParentLoggerLevel();
alert('waiting');
alert(
'This will be executed before the second methods returns HEllo'
);
alert(data);
});
},
第二种方法:
async checkParentLoggerLevel() {
alert('inside checkParentLoggerLevel ');
return await axios
.get('url')
.then(() => {
alert('returning hello');
return 'hello';
});
},
我的目标是在第一种方法中将返回的hello
保存到数据变量中。这是行不通的。 另一个问题是在this.checkParentLoggerLevel()
方法调用代码执行继续并且不等待返回的值之后。
发生这种情况是因为在checkParentLoggerLevel
中您没有等待axios
promise 完成。 你可以这样做:
async checkParentLoggerLevel() {
alert('inside checkParentLoggerLevel ');
return await axios
.get('url')
.then((res) => {
return 'hello';
});
}
此外,您需要在updateLevel
中等待,例如:
async updateLevel() {
axios
.post(url)
.then(async (res) => {
var data = await this.checkParentLoggerLevel();
alert("This will be executed before the second methods returns HEllo");
alert(data);
});
}
你应该链接承诺,所以:
updateLevel() {
axios
.post(url)
.then(res => {
return this.checkParentLoggerLevel.then(data => ([res, data]);
})
.then(([res, data]) => {
// here
});
}
或者简单地使用异步等待:
async updateLevel() {
const res = await axios.post(url);
const data = await this.checkParentLoggerLevel();
// Do whatever you want
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.