promise基本概念
//resolve进入then,reject进入catch
new Promise(function (resolve, reject) {
resolve(123);
}).then(function (res) {
console.log(res)//123
})
new Promise(function (resolve, reject) {
reject(456);
}).catch(function (res) {
console.log(res)//456
})
1.promise状态无法改变
new Promise(function (resolve, reject) {//console.log(123)
resolve(123);
reject(456)
}).then(function (res) {
console.log(res)//123
}).catch(function (err) {
console.log(err)
})
new Promise(function (resolve, reject) {//console.log(456)
reject(456);
resolve(123);
}).then(function (res) {
console.log(res)
}).catch(function (err) {
console.log(err)
})
2.如果.then(function (res)) res不是个函数,会发生值穿透,进入下一个then
new Promise(function (resolve, reject) {
resolve(123);
}).then('asadass2').then(function (res) {
console.log(res)//123
})
3.promise是个同步.then.catch是个异步
new Promise(function (resolve) {//1,2,456
resolve(456);
console.log(1)
}).then(function (res) {
console.log(res)
})
console.log(2)
4 链式调用then,上一个then的返回值是下一个then接收到的参数,如返回错误,返回reject的promise
//第一个then才能接收到 123 第二个then没有值的,返回undefined ,如果想要第二then有值,
//只能return
new Promise(function (resolve, reject) {
resolve(123);
}).then(function (res) {
console.log(res)//123
}).then(function (res) {
console.log(res)//undefined
})
//正确写法
new Promise(function (resolve, reject) {
resolve(123);
}).then(function (res) {
console.log(res)//123
return 456
}).then(function (res) {
console.log(res)//456
})
注意:promise内部使用try catch,所以错误信息 (throw new Error(‘err’))抛出错误才会进入catch,如果是(return new Error(‘err’)),则进入catch
5.then的回调里return一个promise进入等待状态,直到return的promise状态改变
new Promise(function (resolve) {
resolve();
}).then(function (res) {
return new Promise(function(resolve){
setTimeout(function(){
resolve(4)
},3000)
})
}).then(function (res) {
console.log(res)会等到三秒后才会返回4
})