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