1 概念
1.1 定义
- 抽象表达:
- Promise 是一门新的技术(ES6 规范)
- Promise 是 JS 中进行异步编程的新解决方案,旧方案是单纯使用回调函数
- 具体表达:
- 从语法上来说: Promise 是一个构造函数
从功能上来说: Promise 对象用来封装一个异步操作并可以获取其成功/失败的结果值
1.2. 状态改变
一个 Promise 必然处于以下几种状态之一:
待定(pending): 初始状态,既没有被兑现,也没有被拒绝。
- 已兑现(fulfilled): 意味着操作成功完成。
- 已拒绝(rejected): 意味着操作失败。
说明: 只有这 2 种, 且一个 promise 对象只能改变一次。无论变为成功还是失败, 都会有一个结果数据。成功的结果数据一般称为 value, 失败的结果数据一般称为 reason
let promise = new Promise((resolve, reject) => {
// do something
if (xxx) {
// 将参数返回,供then方法使用
resolve("value");
} else {
// 将参数返回,供then方法使用
reject("error");
}
});
- pending 变为 resolved
- pending 变为 rejected
1.3 Promise基本流程
1.4 使用举例
// 1) 创建 promise 对象(pending 状态), 指定执行器函数
const p = new Promise((resolve, reject) => {
// 2) 在执行器函数中启动异步任务
setTimeout(() => {
const time = Date.now();
// 3) 根据结果做不同处理
// 3.1) 如果成功了, 调用 resolve(), 指定成功的 value, 变为 resolved 状 态
if (time % 2 === 1) {
resolve("成功的值:" + time);
} else {
// 3.2) 如果失败了, 调用 reject(), 指定失败的 reason, 变为rejected 状态
reject("失败的值:" + time);
}
}, 2000);
});
// 4) 能 promise 指定成功或失败的回调函数来获取成功的 vlaue 或失败的 reason
p.then(
(value) => {
// 成功的回调函数 onResolved, 得到成功的 vlaue
console.log("成功! ", value);
},
(reason) => {
// 失败的回调函数 onRejected, 得到失败的 reason
console.log("失败! ", reason);
}
);
1.5 解决回调地狱
回调函数
A callback is a function that is passed as an argument to another function and is executed after its parent function has completed.
function sayhello (name, callback) {
console.log(name);
callback();
};
//回调地狱
sayhello("first", function () {
sayhello("second", function () {
sayhello("third", function () {
console.log("end");
});
});
});
Promisefy
const promisefy = fn => {
return function(...args) {
return new Promise((resolve, reject) => {
args.push((err, result) => {
if (err) {
reject(err);
}
resolve(result);
});
fn.apply(this, args);
});
};
};
2 API
2.1 构造函数
Promise 构造函数: Promise (excutor) {}
executor
函数: 执行器(resolve, reject) => {}
resolve
函数: 内部定义成功时我们调用的函数value => {}
reject
函数: 内部定义失败时我们调用的函数reason => {}
说明: executor 会在 Promise 内部立即同步调用,异步操作在执行器中执行
let promise = new Promise(function(resolve) {
console.log("Promise");
resolve();
console.log("!!!")
});
promise.then(function() {
console.log("resolved.");
});
console.log("Hi!");
// Promise
// !!!
// Hi!
// resolved
2.2 then
Promise.prototype.then
方法:(onResolved, onRejected) => {}
onResolved
函数: 成功的回调函数(value) => {}
onRejected
函数: 失败的回调函数(reason) => {}
说明: 指定用于得到成功 value 的成功回调和用于得到失败 reason 的失败回调。返回一个新的 promise 对象,
2.3 catch
Promise.prototype.catch
方法: (onRejected) => {}
onRejected
函数: 失败的回调函数(reason) => {}
说明: then()
的语法糖, 相当于: then(undefined, onRejected)
,也返回一个新的 promise 对象
let p = new Promise((resolve, reject) => {
//修改 promise 对象的状态
reject('error');
});
//执行 catch 方法
p.catch(reason => {
console.log(reason);
});
2.4 resolve
Promise.resolve
方法:(value) => { }
- value: 成功的数据 或 promise 对象
说明: 返回一个成功/失败的 promise 对象
- 如果传入的参数为非 Promise 类型的对象, 则返回的结果为成功 promise 对象
如果传入的参数为 Promise 对象, 则参数的结果决定了 resolve 的结果
let p2 = Promise.resolve(new Promise((resolve, reject) => {
resolve('OK');
// reject('Error');
}));
console.log(p2);//Promise { 'OK' }
p2.then(res=>console.log(res)) //OK
2.5 reject
Promise.reject
方法:(reason) => { }
reason: 失败的原因
说明: 返回一个失败的 promise 对象
let p2 = Promise.resolve(new Promise((resolve, reject) => {
// resolve('OK');
reject('Error');
}));
console.log(p2);//Promise { <rejected> 'Error' }
p2.catch(res=>console.log(res)) //Error
2.6 all
Promise.all
方法: (promises) => { }
promises
: 包含 n 个 promise 的数组
说明: 返回一个新的 promise, 只有所有的 promise 都成功才成功, 只要有一个失败了就直接失败。
let p1 = new Promise((resolve, reject) => {
resolve('OK');
})
let p2 = Promise.resolve('Success');
let p3 = Promise.resolve('Oh Yeah');
const result = Promise.all([p1, p2, p3]);
2.7 race
Promise.race
方法:(promises) => {}
- promises: 包含 n 个 promise 的数组
说明: 返回一个新的 promise,race 就是竞速的意思,最快返回的 promise 的结果状态就是最终的结果状态。