Ram*_*gov 2 javascript promise async-await ecmascript-6
在我的项目中,我使用 promise(下面的代码)pending,当我使用 keyword 时,该 promise 怎么可能await。有人可以帮我弄清楚,我做错了什么吗?
const getTs = async () => {
const response = await axios.get('...')
.then(res => res.data)
.catch(() => 'ERROR');
return response;
};
console.log(getTs()); // Promise { <pending> }Run Code Online (Sandbox Code Playgroud)
The awaitdo 只停止执行async functionbody,没有别的。调用者没有被阻塞,代码仍然是异步的,你会得到一个承诺。如果要记录结果,则必须等待。
const getTs = () => axios.get('...').then(res => res.data).catch(() => 'ERROR');
getTs().then(console.log);
// ^^^^^
Run Code Online (Sandbox Code Playgroud)
或者
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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8274 次 |
| 最近记录: |