promise 和 await

<!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 - 简书

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值