[英]Return resolve-value from async function
在项目中,我使用的承诺(下面的代码),它是如何可能,这一承诺仍然pending
,当我用关键字await
。 有人可以帮我弄清楚我在做什么错吗?
const getTs = async () => { const response = await axios.get('...') .then(res => res.data) .catch(() => 'ERROR'); return response; }; console.log(getTs()); // Promise { <pending> }
await
只会停止async function
主体的执行,而不会停止其他任何事情。 调用者未被阻止,代码仍然是异步的,您将获得一个诺言。 如果要记录结果,则必须等待。
const getTs = () => axios.get('...').then(res => res.data).catch(() => 'ERROR');
getTs().then(console.log);
// ^^^^^
要么
async function getTs() {
try {
const res = await axios.get('...');
return res.data;
} catch (e) {
return 'ERROR';
}
}
async function main() {
const response = await getTs();
// ^^^^^
console.log(response)
}
main();
一旦请求得到解决, getTs
将被解决。 因此,您必须等待响应:
const getTs = async () => {
const response = await axios.get('...')
.then(res => res.data)
.catch(() => 'ERROR');
return response;
};
getTs().then(response => console.log(response));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.