Promise基本使用

Promise 概述

Promise 是 ES6 中新增的一个对象,通过 Promise 就可以实现,用 同步 的流程来表示异步的操作,通过 Promise 就可以避免回调函数层层嵌套(回调地狱)的问题。

MDN:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise

创建 Promise 对象

new Promise(function(resolve, reject){});

promise 对象不是异步的, 只要创建 promise 对象就会立即执行存放的代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script>
        console.log("1");

        let promise = new Promise(function (resolve, reject) {
            console.log("2");
        });

        console.log("3");
    </script>
</head>
<body>
</body>
</html>

image-20220226133521786

Promise 是如何实现通过同步的流程来表示异步的操作的, promise 对象是通过状态的改变来实现的, 只要状态发生改变就会自动触发对应的函数

Promise 对象三种状态

  • pending:默认状态,只要没有告诉 promise 任务是成功还是失败就是 pending 状态

image-20220226162548000

image-20220226162537507

  • fulfilled(resolved): 只要调用 resolve 函数, 状态就会变为 fulfilled, 表示操作成功
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script>
        let promise = new Promise(function (resolve, reject) {
            resolve();
        });

        console.log(promise);
    </script>
</head>
<body>
</body>
</html>

image-20220226162627543

  • rejected: 只要调用 rejected 函数, 状态就会变为 rejected, 表示操作失败
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script>
        let promise = new Promise(function (resolve, reject) {
            reject();
        });

        console.log(promise);
    </script>
</head>
<body>
</body>
</html>

image-20220226162703163

注意点: 状态一旦改变既不可逆, 既从 pending 变为 fulfilled, 那么永远都是 fulfilled,既从 pending 变为 rejected, 那么永远都是 rejected

监听 Promise 状态改变

我们还可以通过函数来监听状态的变化。

  • resolved --> then()
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script>
        let promise = new Promise(function (resolve, reject) {
            resolve();
        });

        promise.then(function () {
            console.log("then");
        });

        promise.catch(function () {
            console.log("catch");
        });
    </script>
</head>
<body>
</body>
</html>

image-20220226162836409

  • rejected --> catch()
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script>
        let promise = new Promise(function (resolve, reject) {
            reject();
        });

        promise.then(function () {
            console.log("then");
        });

        promise.catch(function () {
            console.log("catch");
        });
    </script>
</head>
<body>
</body>
</html>

image-20220226162944262

posted @ 2022-02-26 23:57  BNTang  阅读(79)  评论(0)    收藏  举报