Promise-race方法

Promise 的 race 静态方法

  • race 方法接收一个数组
  • 如果数组中有多个 Promise 对象, 谁先返回状态就听谁的, 后返回的会被抛弃
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script>
        let p1 = new Promise(function (resolve, reject) {
            resolve("111");
            // reject("aaa");
        });
        let p2 = new Promise(function (resolve, reject) {
            setTimeout(function () {
                resolve("222");
                // reject("bbb");
            }, 5000);
        });
        let p3 = new Promise(function (resolve, reject) {
            setTimeout(function () {
                resolve("333");
                // reject("ccc");
            }, 3000);
        });
        Promise.race([p1, p2, p3]).then(function (value) {
            console.log("成功", value);
        }).catch(function (e) {
            console.log("失败", e);
        });
    </script>
</head>
<body>
</body>
</html>
  • 如果数组中不是 Promise 对象, 那么会直接执行 then 方法
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script>
        let obj = {
            name: "BNTang"
        };
        Promise.race([obj]).then(function (value) {
            console.log("成功", value);
        }).catch(function (e) {
            console.log("失败", e);
        });
    </script>
</head>
<body>
</body>
</html>

应用场景

  • 接口调试, 超时处理
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>promise-race方法</title>
</head>
<body>
<script>
    let url = "https://a.msstatic.com/huya/main3/assets/img/index-bg_59f9c.jpg";

    function loadImage(url) {
        return new Promise(function (resolve, reject) {
            let oImg = new Image();
            setTimeout(function () {
                oImg.src = url;
            }, 5000);
            oImg.onload = function () {
                resolve(oImg);
            }
            oImg.onerror = function () {
                reject("图片加载失败了");
            }
        });
    } 

    function timeout() {
        return new Promise(function (resolve, reject) {
            setTimeout(function () {
                reject("超时了");
            }, 3000);
        });
    }

    Promise.race([loadImage(url), timeout()]).then(function (value) {
        console.log("成功", value);
    }).catch(function (e) {
        console.log("失败", e);
    });
</script>
</body>
</html>
posted @ 2022-03-01 23:28  BNTang  阅读(139)  评论(0编辑  收藏  举报