Promise 菜鸟教程|Promise和then之间的关系
peromise 语法1
注意:new Peromise((fun1)=>{})的的fun1带着的参数与 then((data1){}) 中data1对应,按顺序对应
let promise = new Peromise((fun1) =>{
//这里面放入异步请求代码 自己定fun1在什么情况下执行 如下实例代码所示
});
//取用Peromise结果
promise.then((data1)=>{
//异步请求完 同步请求操作
});
// 或着
promise.then(function(data1){
//异步请求完 同步请求操作
});
示列代码1
req0:function(){
let promise = new Promise((resolve) => {
//进来之后,状态为pending
console.log('111'); //这行代码是同步的
uni.request({
// token 授权 api 服务器地址
url : GraceRequestConfig.apiBaseUrl + "/sys/checkedToken",
// 请求方式
method : "GET",
// headers
header : {'content-type' : 'application/x-www-form-urlencoded'},
// 返回值类型
dataType : "json",
success : (res)=>{
console.log('333');
resolve(res.data);
},
fail : (error)=>{},
complete : (res) =>{}
});
})
return promise;
},
req2:function(){
this.req0().then((data) =>{
console.log('222');
console.log(data);
});
}
打印结果
peromise 语法2
注意:fun1和fun2执行一个就不会执行另外一个,执行了其中一个fun,Peromise过程就结束了,
let promise = new Peromise((fun1,fun2) =>{
//这里面放入异步请求代码 自己定fun1在什么情况下执行 如下实例代码所示
});
//取用Peromise结果
promise.then(
(data1)=>{
//异步请求完 同步请求操作
},
(data2)=>{
//异步请求完 同步请求操作
}
);
实例代码2
req0:function(){
let promise = new Promise((fun1,fun2) => {
//进来之后,状态为pending
console.log('111'); //这行代码是同步的
uni.request({
// token 授权 api 服务器地址
url : GraceRequestConfig.apiBaseUrl + "/sys/checkedToken",
// 请求方式
method : "GET",
// headers
header : {'content-type' : 'application/x-www-form-urlencoded'},
// 返回值类型
dataType : "json",
success : (res)=>{
console.log('333');
fun1(res.data);
},
fail : (error)=>{
console.log('333');
fun2("fail");
},
complete : (res) =>{}
});
})
return promise;
},
req2:function(){
this.req0().then(
function(data1){
console.log('222');
console.log(data1);
},
function(data2){
console.log('222');
console.log(data2);
}
);
}
打印结果
小编有话说:整篇内容均为个人理解,若有不足,还望海涵。如有版权冲突,请联系小编协商。