[英]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.