ES6之Promise

Promise
Promise 是 ES6 引入的异步编程的新解决方案。语法上 Promise 是一个构造函数,
用来封装异步操作并可以获取其成功或失败的结果。
1) Promise 构造函数: Promise (excutor) {}
2) Promise.prototype.then 方法
3) Promise.prototype.catch 方法
 
 基本使用
复制代码
<!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 对象  默认的2个参数
        const p = new Promise(function(resolve, reject){
            setTimeout(function(){
                //
                // let data = '数据库中的用户数据';
                // resolve 调用这个方法会使用then函数的第一个回调方法
                // resolve(data);

                let err = '数据读取失败';
                reject(err);
            }, 2000);
        });

        //调用 promise 对象的 then 方法  异步执行
        p.then(function(value){
            console.log(value);
        }, function(reason){
            console.error(reason);
        });

        console.log("111");
    </script>
</body>
</html>
复制代码

  异步执行,这里做了个2秒的定时,所以先执行111,2秒时间到之后再执行p中的方法

 结果:

 

 

 Promise封装读取文件
 
复制代码
//1. 引入 fs 模块
const fs = require('fs');

//2. 调用方法读取文件  单任务
// fs.readFile('./resources/为学.md', (err, data)=>{
//     //如果失败, 则抛出错误
//     if(err) throw err;
//     //如果没有出错, 则输出内容
//     console.log(data.toString());
// });

//3. 使用 Promise 封装  异步调用
const p = new Promise(function(resolve, reject){
    fs.readFile("./resources/为学.mda", (err, data)=>{
        //判断如果失败
        if(err) reject(err);
        //如果成功
        resolve(data);
    });
});

p.then(function(value){
    console.log(value.toString());
    console.log("读取文件结束");
}, function(reason){
    console.log("读取失败!!");
});
console.log("正在读取文件");
复制代码

  

catch方法
 
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>catch方法</title>
</head>
<body>
    <script>
        const p = new Promise((resolve, reject)=>{
            setTimeout(()=>{
                //设置 p 对象的状态为失败, 并设置失败的值
                reject("出错啦!");
            }, 1000)
        });

        // p.then(function(value){}, function(reason){
        //     console.error(reason);
        // });

        p.catch(function(reason){
            console.warn(reason);
        });
    </script>
</body>
</html>
复制代码

 

 
 
 
 
 
posted @   安静点--  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
历史上的今天:
2021-11-20 jQuery增删表格数据
2021-11-20 jQuery文档增删
2021-11-20 jQuery爱好选择器
点击右上角即可分享
微信分享提示