Js一直是我喜欢的一个工具,它的便捷,快速,特别喜欢,使用了也有一阵子了,边学边记录,今天记录一下Promise的相关使用问题。
1、Promise是什么?
Promise
- 是一个js用来处理异步函数的语法 (通常网络请求了,什么的需要使用,并且比较频繁)
- 也可以说是js的一个类
2、Promise 语法构成
new Promise(function (resolve, reject) {
console.log("Run");
resolve("run success");
//reject("run fail");
});
Promise 构造函数只有一个参数,是一个函数,这个函数在构造之后会直接被异步运行,所以我们称之为起始函数。起始函数包含两个参数 resolve 和 reject,resolve 和 reject 都是函数,其中调用 resolve 代表一切正常,reject 是出现异常时所调用的
new Promise(function (resolve, reject) {
console.log(1111);
resolve(2222);
}).then(function (value) {
console.log(value);
return 3333;
}).catch(function (err) {
console.log(err);
});
Promise 类有 .then() .catch() 和 .finally() 三个方法,这三个方法的参数都是一个函数,.then() 可以将参数中的函数添加到当前 Promise 的正常执行序列,.catch() 则是设定 Promise 的异常处理序列,.finally() 是在 Promise 执行的最后一定会执行的序列。 .then() 传入的函数会按顺序依次执行,有任何异常都会直接跳到 catch 序列
3、Promise 简单使用
function print(delay, message) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
console.log("开始执行");
if (message){ //如果存在message,返回成功
resolve("执行成功");
}else {//如果不存在message,返回失败
reject("执行失败");
}
}, delay);
});
}
print(1000, "First") //调用print函数
.then(function (success) { //使用then方法传入一个success的函数获取成功时的结果
console.log(success)
})
.catch(function (fail) {//使用catch方法传入一个fail的函数获取失败时的结果
console.log(fail)
});
4、一个网络请求小Demo
function getUserInfo(){
return new Promise(function (resolve, reject){
axios.get('https://randomuser.me/api/')
.then(function(response) {
resolve(response.data)
});
});
}
console.log("第一步")
getUserInfo()
.then(function (success){
console.log(success)
})
.catch(function (error){
console.log(error)
})
console.log("第二步")
console.log("第三步")
大致用法就是这样了,也初步明白了一些简单的知识了吧,未完待续,后续再写一下深入的东西!
----------------------------------------------------------------江山也要伟人扶,神化丹青即画图