async 基本使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
function f1() {
return new Promise(resolve=>{
setTimeout(()=>{
console.log('第一步');
resolve();
}, 1000)
})
}
function f2() {
return new Promise(resolve=>{
setTimeout(()=>{
console.log('第二步');
resolve();
})
}, 1000)
}
/*
f1().then(res=>{
return f2();
}).then(res=>{
console.log('已完成');
}).catch(resError=>{
console.log(resError);
})
*/
// 以上注釋代碼使用 async 實現(xiàn)
(async function(){
// await 表示其后面的函數(shù)(必須是 promise() 函數(shù) 或是 async function)是一個異步操作,下面 N 行的代碼會在這個異步操作完成后再執(zhí)行
await f1();
await f2();
console.log('已完成');
})()
</script>
</body>
</html>
async 傳遞參數(shù)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
function f1() {
return new Promise(resolve=>{
setTimeout(()=>{
resolve('第一步');
}, 1000)
})
}
function f2() {
return new Promise(resolve=>{
setTimeout(()=>{
resolve('第二步');
})
}, 1000)
}
/*
f1().then(res=>{
console.log(res);
return f2();
}).then(res=>{
console.log(res);
console.log('已完成');
}).catch(resError=>{
console.log(resError);
})
*/
// 以上注釋代碼使用 async 實現(xiàn)
// async ()=>{} <=> (async function(){})
(async ()=>{
// await 表示其后面的函數(shù)(必須是 promise() 函數(shù) 或是 async function)是一個異步操作,下面 N 行的代碼會在這個異步操作完成后再執(zhí)行
var res1 = await f1();
console.log(res1);
var res2 = await f2();
console.log(res2);
console.log('已完成');
})()
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
var person = {
say: async()=>{
var res = await (()=>{
return new Promise(resolve=>{
setTimeout(function() {
resolve('先說話');
}, 1000)
});
})();
console.log(res);
},
walk: async function() {
var res = await (()=>{
return new Promise(resolve=>{
setTimeout(function() {
resolve('再走路');
}, 1000)
});
})();
console.log(res);
}
}
/* 這種方式會報錯
(async function() {
await person.say();
await person.walk();
})()
*/
var fn = async function() {
await person.say();
await person.walk();
};
fn();
</script>
</body>
</html>
async 錯誤處理