一、介绍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执行过程
- 创建一个Promise 对象,同步执行起始函数,此时padding状态
- 获取起始函数响应数据,设置Promise状态,失败状态设置为 rejected ,成功设置为 fulfilled(Promise的状态一旦改变,就不会再变)
- 当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);
}
}
};
})
参考文章