验证中...
async和await实现异步函数同步调用.html
Raw Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
//async函数的await命令后面,可以是 Promise 对象和原始类型的值(数值、字符串和布尔值,但这时会自动转成立即 resolved 的 Promise 对象)
//进一步说,async函数完全可以看作多个异步操作,包装成的一个 Promise 对象,而await命令就是内部then命令的语法糖。
(function() {
function timeout(ms, value) {
return new Promise((resolve) => {
setTimeout(resolve, ms, value + 'chen ye');
});
}
async function asyncPrint(value, ms) {
const res = await timeout(ms, value);
console.log(res);//5秒钟后打印出 hello chen ye
}
asyncPrint('hello ', 5000);
})();
(function() {
async function timeout(ms) {
await new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function asyncPrint(value, ms) {
await timeout(ms);
console.log(value);//1秒钟后打印出hello world
}
asyncPrint('hello world', 1000);
})();
</script>
</body>
</html>

Comment list( 0 )

You need to Sign in for post a comment

Help Search