在我的项目中,当我使用关键字pending
时,我使用promise(下面的代码),如何可能,这个承诺仍然是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));