[英]Return value from async / await function
我對這個 async/await 的工作方式有點困惑
我有一些像這樣的功能
async getDataFromDB() {
let response = await fetch('...');
let data = await response.json();
return data;
}
async getData() {
if (...) {
let response = await this.getDataFromDB().then((res) => {
let response = await this.returnHello();
return response;
});
return response;
} else {
// ...
}
}
returnHello() {
return 'hello';
}
現在當我console.log(getData())
它應該返回'hello'
但它返回Promise {<pending>}
基本上我想要的結果是
const something = this.getData();
並且字符串設置正確
async
函數總是返回承諾。 async
/ await
存在是為了簡化使用 promise 的語法,而不是消除 promise。
使用async
函數的代碼需要在承諾上調用.then
,或者本身就是一個async
函數並await
承諾。
this.getData()
.then(something => {
});
const something = await this.getData();
咱們試試吧
async showData(){
console.log(await getData())
}
並運行
showData()
或在return response;
之前放置console.log(response)
return response;
在getData()
函數中。
希望能幫到你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.