<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<style>
</style>
<body>
<script>
const myFun = async () => {
return new Promise(resolve => {
setTimeout(() => { // 用定时器模拟异步请求
const data = [
{ id: 1, name: 'xiaoming', age: 11 },
{ id: 2, name: 'xiaohong', age: 22 },
{ id: 3, name: 'xiaogang', age: 33 },
];
resolve(data);
}, 1000);
});
}
const myFun2 = async () => {
res = await myFun();
console.log('res:', res);
}
myFun2();
</script>
</body>
</html>
原理:使用promise来包裹setTimeout定时器,因为promise对象可以将异步操作以同步操作的流程表达出来,同时避免了层层嵌套的回调函数。