Promise 的使用

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

</body>

<script>
    // 异步结果返回
    function takelongtime(n) {
        return new Promise(resolve => {
            setTimeout(() => {
                resolve(n + 2000)
            }, n);
        })
    }

    // 异步请求一
    function step1(n) {
        return takelongtime(n)
    }

    // 异步请求二
    function step2(n) {
        return takelongtime(n)
    }

    // 异步请求三
    function step3(n) {
        return takelongtime(n)
    }

    // 方式一
    function mode1(timer) {
        Promise.all([step1(2000), step2(4000), step3(6000)]).then(res => {
            console.log(res);
            clearInterval(timer);
        });
    }

    // 方式二
    async function mode2(timer) {
        let data_all = await Promise.all([step1(2000), step2(4000), step3(6000)]);

        console.log(data_all);
        clearInterval(timer);
    }

    // 方式三
    async function mode3(timer) {
        let step1_res = await step1(2000);
        let step2_res = await step2(4000);
        let step3_res = await step3(6000);

        console.log(step1_res, step2_res, step3_res);
        clearInterval(timer);
    }

    // 初始化
    function init() {
        var time = 0
        var timer = setInterval(() => {
            console.log(time += 1);
        }, 1000);

        mode1(timer);
        // mode2(timer);
        // mode3(timer);
    }


    init();

</script>

</html>
posted @ 2022-09-22 14:55  进阶的哈姆雷特  阅读(13)  评论(0编辑  收藏  举报