Js Promise

Js Promise

形式

const p = new Promise((resolve, reject) => {
  if(true)
    resolve(); //将promise对象的状态设置为成功
  else 
    reject(); //将promise对象的状态设置失败
});

resolve 异步执行成功调用

reject 异步执行失败调用

以上两个参数都是函数类型的数据

p.then(() => {
	//成功执行
}, () => {
	//失败执行
});

试一手

<!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>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
        crossorigin="anonymous">
</head>

<body>
    <div class="container">
        <h1>Ajax</h1>
        <button class="btn btn-primary">点击发送请求</button>
    </div>

    <script>
        const btn = document.querySelector('button');
        btn.addEventListener('click', function () {
            const xhr = new XMLHttpRequest();
            xhr.open('GET', 'https://api.apiopen.top/getJoke');
            xhr.send();
            //readystate
            //0 为初始状态
            //1 表示open执行完毕
            //2 表示send执行完毕
            //3 表示服务端返回部分结果
            //4 表示服务端返回所有结果
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    //判断响应判断码 200 404...
                    //2xx都表示成功
                    if (xhr.status >= 200 && xhr.status < 300) {
                        // 响应行
                        console.log(xhr.status);//状态码
                        console.log(xhr.statusText);//状态字符串
                        console.log(xhr.getAllResponseHeaders());//所有响应头
                        console.log(xhr.response);//响应体


                    } else {
                        console.log('Error');
                    }
                }
            }
        })
    </script>

</body>

</html>

以上为一般ajax的基础操作,然后我们来试试使用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>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
        crossorigin="anonymous">
</head>

<body>
    <div class="container">
        <h1>Ajax</h1>
        <button class="btn btn-primary">点击发送请求</button>
    </div>

    <script>
        const btn = document.querySelector('button');
        btn.addEventListener('click', function () {
            const p = new Promise((resolve, reject) => {
                const xhr = new XMLHttpRequest();
                xhr.open('GET', 'https://api.apiopen.top/getJoke');
                xhr.send();

                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4) {

                        if (xhr.status >= 200 && xhr.status < 300) {
                            resolve(xhr.response);
                        } else {
                            reject(xhr.status)
                        }
                    }
                }
            });
            p.then(val => {
                console.log(val);
            }, err => {
                console.warn(err);
            })
        });


    </script>

</body>

</html>

当然啊,这样看着很乱,所以我们可以封装一手,下面就只写js代码了

function sendAjax(url) {
    return new Promise((resolve, reject) => {
        const x = new XMLHttpRequest();
        x.responseType = 'json'; // 设置响应体为JSON格式
        x.open('GET', url);
        x.send();
        x.onreadystatechange = function () {
            if (x.readyState === 4) {
                if (x.status >= 200 && x.status < 300) {
                    resolve(x.response);
                } else {
                    reject(x.status);
                }
            }
        }
    });
}

// 直接调用
sendAjax('https://api.apiopen.top/getJoke').then(val => {
    console.log(val);
}, err => {
    console.log(err);
})

Promise的状态

实例对象的一个属性「promiseState」

这个属性有三个状态

  • Pending 未决定的(默认状态)
  • Resolved / Fulfilled 成功
  • Rejected 失败

状态的变换有且只有两种Pending->Resolved和Pending->Rejected而且只能变换一次

实例对象的一个属性「promiseResult」

保存着异步请求成功或者失败的结果

只有resolve和reject能修改,当然强行throw也可以

手撕Promise

function Promise(excutor) {

    this.PromiseState = 'pending';
    this.PromiseResult = null;

    this.callbacks = [];

    const self = this;

    function resolve(data) {
        if (self.PromiseState !== 'pending') return;
        self.PromiseState = 'fullfilled';
        self.PromiseResult = data;

        setTimeout(() => {
            self.callbacks.forEach(item => {
                item.onResolved(data);
            })
        })
    }

    function rejected(data) {
        if (self.PromiseState !== 'pending') return;
        self.PromiseState = 'rejected';
        self.PromiseResult = data;

        setTimeout(() => {
            self.callbacks.forEach(item => {
                item.onRejected(data);
            })
        })
    }

    try {
        excutor(resolve, rejected);
    } catch (error) {
        rejected(error)
    }

}

Promise.prototype.then = function (onResolved, onRejected) {
    const self = this;

    if (typeof onRejected !== 'function') {
        onRejected = reason => {
            throw reason;
        }
    }

    if (typeof onResolved !== 'function') {
        onResolved = value => value;
    }

    return new Promise((resolve, rejected) => {

        function callback(type) {
            try {
                let result = type(self.PromiseResult);
                if (result instanceof Promise) {
                    result.then(v => {
                        resolve(v);
                    }, e => {
                        rejected(e);
                    })
                } else {
                    resolve(result);
                }
            } catch (e) {
                rejected(e);
            }
        }

        if (this.PromiseState === 'fullfilled') {
            setTimeout(() => { callback(onResolved); })

        }

        if (this.PromiseState === 'rejected') {
            setTimeout(() => { callback(onRejected); })
        }

        if (this.PromiseState === 'pending') {

            this.callbacks.push({
                onResolved: function () {
                    callback(onResolved);
                },
                onRejected: function () {
                    callback(onRejected);
                }
            });
        }
    })
}

Promise.prototype.catch = function (onRejected) {
    return this.then(undefined, onRejected);

}

Promise.resolve = function (value) {
    return new Promise((resolve, reject) => {
        if (value instanceof Promise) {
            value.then(v => {
                resolve(v);
            }, e => {
                reject(e);
            })
        } else {
            resolve(value);
        }
    })
}

Promise.reject = function (reason) {
    return new Promise((resolve, reject) => {
        reject(reason);
    })
}

Promise.all = function (promises) {
    return new Promise((resolve, reject) => {
        let count = 0;
        let arr = [];
        for (let i = 0; i < promises.length; ++i) {
            promises[i].then(v => {
                count++;
                arr[i] = v;
                if (count === promises.length) {
                    resolve(arr);
                }
            }, e => {
                reject();
            })
        }
    })
}

Promise.race = function (promises) {
    return new Promise((resolve, reject) => {
        for (let i = 0; i < promises.length; ++i) {
            promises[i].then(v => {
                resolve(v);
            }, e => {
                reject(e);
            })
        }
    })
}
### JavaScriptPromise 的用法与示例 #### 什么是 PromisePromise 是一种用于处理异步操作的对象,它表示一个最终会完成或者失败的操作的结果。通过使用 Promise,可以更清晰地管理复杂的异步流程。 #### 基本结构 Promise 对象有三种状态:`pending`(等待)、`fulfilled`(已成功)和 `rejected`(已失败)。当 Promise 被执行时,其状态会从 `pending` 变为 `fulfilled` 或者 `rejected`[^1]。 以下是基本语法: ```javascript const myPromise = new Promise((resolve, reject) => { // 异步操作逻辑 if (/* 条件 */) { resolve(value); // 成功时调用 } else { reject(error); // 失败时调用 } }); ``` #### 使用 `.then()` 和 `.catch()` `.then()` 方法用于处理成功的回调,而 `.catch()` 则捕获错误并提供相应的处理机制。 ```javascript myPromise .then(result => console.log(`Success: ${result}`)) // 处理成功的情况 .catch(error => console.error(`Error: ${error.message}`)); // 处理失败的情况 ``` #### 链式调用 由于返回的是一个新的 Promise 实例,因此可以通过链式调用来简化多个异步操作的顺序执行。 ```javascript new Promise(resolve => setTimeout(() => resolve(1), 1000)) .then(val => val * 2) .then(val => val + ' is the result') .then(console.log); // 输出:"2 is the result" ``` #### 并行执行多个 Promise 如果需要同时启动多个异步任务,则可以使用 `Promise.all([])` 方法来等待所有的 Promise 完成后再继续下一步。 ```javascript Promise.all([ fetch('/api/data1').then(response => response.json()), fetch('/api/data2').then(response => response.json()) ]) .then(([data1, data2]) => { console.log(data1, data2); }) .catch(err => console.error('An error occurred:', err)); ``` #### 错误处理的最佳实践 为了更好地控制异常传播路径,在设计复杂的应用程序时应始终考虑如何优雅地处理潜在的错误情况。 ```javascript function fetchData(url) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onload = () => (xhr.status === 200 ? resolve(xhr.responseText) : reject(new Error('Failed'))); xhr.onerror = () => reject(new Error('Network Error')); xhr.send(); }); } fetchData('/some/valid/url') .then(data => JSON.parse(data)) .then(processedData => console.log(processedData)) .catch(e => alert(e.message)); ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值