<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const src1 = 'url 1111'
const src2 = 'url 2222'
//模拟延时
function sleep(sleepTime) {
var start = new Date().getTime();
while (true) {
if (new Date().getTime() - start > sleepTime) {
break;
}
}
}
//模拟http请求
function http_request(src) {
return new Promise(function (resolve, reject) {
sleep(1000)
resolve(src)
})
}
//await
async function load() {
const result1 = await http_request(src1)
console.log('load result1', result1)
const result2 = await http_request(src2)
console.log('load result2', result2)
}
//不用await
function load2() {
http_request(src1).then(data => {
console.log('load2 result1', data)
})
console.log('load2 11111');
http_request(src2).then(data => {
console.log('load2 result2', data)
})
console.log('load2 22222');
}
console.log('time1', new Date());
load()
console.log('time2', new Date());
load2()
console.log('time3', new Date());
</script>
<pre>
结果:
time1 Mon May 02 2022 17:21:07 GMT+0800 (中国标准时间)
time2 Mon May 02 2022 17:21:08 GMT+0800 (中国标准时间)
load2 11111
load2 22222
time3 Mon May 02 2022 17:21:10 GMT+0800 (中国标准时间)
load result1 url 1111
load2 result1 url 1111
load2 result2 url 2222
load result2 url 2222
</pre>
</body>
</html>
异步解决方案----Promise与Await - 简书