[英]Return resolve-value from async function
In my project I use promise (code below), how it is possible, that promise still pending
, when I used keyword await
. 在项目中,我使用的承诺(下面的代码),它是如何可能,这一承诺仍然
pending
,当我用关键字await
。 Can someone help me figure out, what I'm doing wrong? 有人可以帮我弄清楚我在做什么错吗?
const getTs = async () => { const response = await axios.get('...') .then(res => res.data) .catch(() => 'ERROR'); return response; }; console.log(getTs()); // Promise { <pending> }
The await
does only stop the execution of the async function
body, nothing else. await
只会停止async function
主体的执行,而不会停止其他任何事情。 The caller is not blocked, the code is still asynchronous, and you get back a promise. 调用者未被阻止,代码仍然是异步的,您将获得一个诺言。 If you want to log the result, you have to wait for it.
如果要记录结果,则必须等待。
const getTs = () => axios.get('...').then(res => res.data).catch(() => 'ERROR');
getTs().then(console.log);
// ^^^^^
or 要么
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
will be resolved once the request is resolved. 一旦请求得到解决,
getTs
将被解决。 So you have to await the response like : 因此,您必须等待响应:
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.