回调函数:作为参数传递的函数,某一时刻,用来回调
在 setTimeout 中传递了一个箭头函数,在 3s 后调用了他
setTimeout(() => {
console.log("print...");
}, 3000);
Promise 用于解决多层回调嵌套,产生回调地狱的情况,它采用链式调用的写法代替回调函数嵌套的写法
1.Promise 的构造函数
Promise 构造器主要用于包装不支持promise(返回值不是Promise)的函数,它接收两个参数 resolve, reject 分别是成功的回调和失败的回调
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
let result = 'foo'
resolve(result); // 作为promise的值
console.log("DONE") // 会执行
result = 'change' // result的值会改变但是 promise1 里的值不会再变化
}, 300);
});
console.log(promise1)
/* Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: "foo" */
- Promise.prototype 上包含一个 .then() 方法
- .then() 方法用来预先指定成功和失败的回调函数
- p.then( result => { }, error =>{ }), 成功的回调是必选的、失败的回调是可选的
this.$axios({
url: "/daas/qydj/select_tzrTo_pdqylx",
method: "get",
params: _baseojb
}).then((res) => {
console.log(res)
});
2.手写一个Promise构造函数
class Promise {
constructor(executor) {
// 初始化一个状态为 pending 的 Promise
this.status = "pending";
this.value = undefined;
this.reason = undefined;
// 成功回调
this.onResolvedCallbacks = [];
// 失败回调
this.onRejactedCallbacks = [];
let resolve = (value) => {
if (this.status === "pending") {
this.value = value;
this.status = "fulfilled";
}
this.onResolvedCallbacks.forEach((fn) => fn());
};
let reject = (reason) => {
if (this.status === "pending") {
this.value = reason;
this.status = "rejected";
}
this.onRejactedCallbacks.forEach((fn) => fn());
};
}
// 传入的成功回调和失败回调
then(onFulfilled, onRejected) {
// 如果为异步操作,将后续函数放入成功回调的数组,在resolve后遍历该数组调用
if (this.status == "pending") {
this.onResolvedCallbacks.push(() => {
onFulfilled(this.value);
});
this.onRejactedCallbacks.push(() => {
// Promise的返回值作为回调的参数
onRejected(this.value);
});
}
// 如果是同步函数,则直接进行后面的操作
if ((this.status = "fullfilled")) {
onFulfilled(this.value);
}
if ((this.status = "rejected")) {
onRejected(this.value);
}
}
}
在then() 语句块中需要有返回值,后面的 then 才能接收到参数,返回值可以是 Promise 也可以不是
let p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("hhhhh");
}, 2000);
});
p1.then((res) => {
console.log(res); // hhhhh
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("xxxxx");
}, 2000);
});
}).then((res) => {
console.log(res); // xxxxx
});