专业的编程技术博客社区

网站首页 > 博客文章 正文

JavaScript,ES6,Promise(将发生的事),异步编程的新解决方案

baijin 2024-10-27 19:21:07 博客文章 8 ℃ 0 评论

Promise(将发生的事)

Promise是ES6引入的异步编程的新解决方案,语法上 Promise 是一个构造函数,用来封装异步操作并可以获取其成功或失败的结果。

1、Promise构造函数: Promise (excutor) {};

2、Promise.prototype.then 方法;

3、Promise.prototype.catch 方法。

参考:Promise异步编程 async await,代码

代码案例

案例1:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise基本语法</title>
</head>
<body>
    <script>
        //实例化 Promise 对象
        const p = new Promise(function(resolve, reject){
            setTimeout(function(){
                //
                // let data = '数据库中的用户数据';
                // resolve
                // resolve(data);

                let err = '数据读取失败';
                reject(err);
            }, 1000);
        });
        //调用 promise 对象的 then 方法
        p.then(function(value){
            console.log(value);
        }, function(reason){
            console.error(reason);
        })
    </script>
</body>
</html>

案例2:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发送 AJAX 请求</title>
</head>
<body>
    <script>
        // 接口地址: https://api.apiopen.top/getJoke
        const p = new Promise((resolve, reject) => {
            //1. 创建对象
            const xhr = new XMLHttpRequest();
            //2. 初始化
            xhr.open("GET", "https://api.apiopen.top/getJ");
            //3. 发送
            xhr.send();
            //4. 绑定事件, 处理响应结果
            xhr.onreadystatechange = function () {
                //判断
                if (xhr.readyState === 4) {
                    //判断响应状态码 200-299
                    if (xhr.status >= 200 && xhr.status < 300) {
                        //表示成功
                        resolve(xhr.response);
                    } else {
                        //如果失败
                        reject(xhr.status);
                    }
                }
            }
        })
        //指定回调
        p.then(function(value){
            console.log(value);
        }, function(reason){
            console.error(reason);
        });
    </script>
</body>
</html>

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表