Promise学习记录

一、介绍Promise

什么是 Promise 

Promise 是一个 ECMAScript 6 提供的类,目的是更加优雅地书写复杂的异步任务。

Promise 对象表示异步操作最终的完成(或失败)以及其结果值。

Promise优缺点

  • 链式操作减低了编码难度
  • 代码可读性明显增强

【示例】如果需分三次依次输出字符串,第一次间隔 1 秒,第二次间隔 4 秒,第三次间隔 3 秒。

【未使用Promise】嵌套层级复杂,出现回调地狱现象

//未使用Promise
setTimeout(function () {
    console.log("First");
    setTimeout(function () {
        console.log("Second");
        setTimeout(function () {
            console.log("Third");
        }, 3000);
    }, 4000);
}, 1000);


【使用Promise】

new Promise<void>(function (resolve, reject) {
      setTimeout(function () {
          console.log("First");
          resolve();
      }, 1000);
    }).then<void>(function () {
        return new Promise(function (resolve, reject) {
            setTimeout(function () {
                console.log("Second");
                resolve();
            }, 4000);
        });
    }).then(function () {
        setTimeout(function () {
            console.log("Third");
        }, 3000);
    });
缺 

二、Promise执行过程

  1. 创建一个Promise 对象,同步执行起始函数,此时padding状态
  2. 获取起始函数响应数据,设置Promise状态,失败状态设置为 rejected ,成功设置为 fulfilled(Promise的状态一旦改变,就不会再变
  3. 当Promise 对象状态为rejected 或 fulfilled 被,Promise对象的then 方法串联的处理程序将被调用

一个 Promise 必然处于以下几种状态【PromiseState】之一:

  • 待定(pending):初始状态,既没有被兑现,也没有被拒绝。
  • 已兑现(fulfilled):意味着操作成功完成。
  • 已拒绝(rejected):意味着操作失败。

三、Promise使用

第一种使用 then


function print(delay:any, message:any) {
    return new Promise<void>(function (resolve, reject) {
        setTimeout(function () {
            console.log(message);
            resolve();
        }, delay);
    });
}

print(1000, "First").then(function () {
    return print(4000, "Second");
}).then(function () {
    print(3000, "Third");
}).catch(function (error) {
      console.log(error);
  });

第二种使用 async await

function print(delay:any, message:any) {
          return new Promise<void>(function (resolve, reject) {
              setTimeout(function () {
                  console.log(message);
                  resolve();
              }, delay);
      });
      }
async function asyncFunc() {
    await print(1000, "First").catch(error=>console.log('捕捉错误......',error));
    await print(4000, "Second");
    await print(3000, "Third");
}
asyncFunc();

记录:

const promiseDemo=new Promise<void>(function (resolve, reject) {
          // 创建 XMLHttpRequest 对象
          const xhttp = new XMLHttpRequest();
          
          // 前端设置是否带cookie
          xhttp.withCredentials = true;
          

          let d={
                  label: 'Fred',
                  type: 'Flintstone'
                };
          //请求体数据
            let params= JSON.stringify(d);

          // 发送请求
          xhttp.open("POST", 'http://localhost:8089/query');

          //setRequestHeader添加HTTP 头部
          xhttp.setRequestHeader("Content-type", "application/json");

          xhttp.send(params);

          //设置响应数据格式
          xhttp.responseType='json'

          xhttp.onreadystatechange = function() {
            //判断XMLHttpRequest 的状态

            // 0:请求未初始化
            // 1:服务器连接已建立
            // 2:请求已收到
            // 3:正在处理请求
            // 4:请求已完成且响应已就绪
            if (this.readyState == 4) {

              if( this.status >= 200&&this.status<=300){
                console.log('success...onreadystatechange',this.readyState,this.response)
                resolve(this.response);
              }else{
                console.log('error...onreadystatechange',this.readyState,this.response)
                reject(this.response);
              }
            }
          };
      })

参考文章 

Promise - JavaScript | MDN (mozilla.org)

JavaScript Promise | 菜鸟教程 (runoob.com)

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值