Promise实例.then()返回的是一个【新的Promise实例】,它的值和状态由什么决定?
1.简单表达:由then()所指定的回调函数执行的结果决定
2.详细表达:
(1)如果then所指定的回调返回的是非Promise值a:
那么【新Promise实例】状态为:成功(fulfilled)成功的value为a
(2)如果then所指定的回调返回的是Promise值p:
那么【新Promise实例】状态\值,都与p一致
(2)如果then所指定的回调抛除异常:
那么【新Promise实例】状态为rejected,reason为抛除的那个异常
中段Promise链:
(1)当使用promise的then链式调用时,在中间中断,不在调用后面的回调函数
(2)办法:在失败的回调函数中返回一个pendding状态的Promise实例
- <script>
-
- function sentAjax(url,data){
-
- return(
-
- new Promise((resolve,reject)=>{
-
- // resolve(1)
-
- let xhr = new XMLHttpRequest()
-
- xhr.onreadystatechange =()=>{
-
- if(xhr.readyState === 4){
-
- if(xhr.status >= 200 && xhr.status<300){
-
- resolve(xhr.response)
-
- }else{
-
- reject('出错了')
-
- }
-
- }
-
- }
-
- // 整理url中的参数
-
- let str=''
-
- for(key in data){
-
- str += `${key}=${data[key]}`
-
- }
-
- xhr.open('GET',url+'?'+ str)
-
- xhr.responseType="json"
-
- xhr.send()
-
- })
-
- )
-
- }
-
- sentAjax('https://api.github.com/search/users',{q:2})
-
- .then(
-
- value=>{
-
- console.log('第一次成功了',value)
-
- return sentAjax('https://api.github.com/search/users',{q:3})
-
- },
-
- reason=>{
-
- console.log('第一次失败了',reason)
-
- return new Promise(()=>{})
-
- }
-
- )
-
- .then(
-
- value=>{
-
- console.log('第二次成功了',value)
-
- return sentAjax('https://api.github.com/search/users',{q:4})
-
- },
-
- reason=>{
-
- console.log(reason)
-
- return new Promise(()=>{})
-
- }
-
- )
-
- .then(
-
- value=>{console.log('第三次成功了',value)},
-
- reason=>{console.log(reason)}
-
- )
-
- </script>
可惜,幸福都类似,悲伤却又千万种
Promise错误穿透:
(1)当使用promise的then链式调用时,可以在最后用catch指定一个失败的回调
(2)当前任何操作出错,都会传到左后失败的回调中处理
备注:如果不存在then的链式调用,就不需要考虑then的错误穿透
- <script>
- function sentAjax(url,data){
- return(
- new Promise((resolve,reject)=>{
- // resolve(1)
- let xhr = new XMLHttpRequest()
- xhr.onreadystatechange =()=>{
- if(xhr.readyState === 4){
- if(xhr.status >= 200 && xhr.status<300){
- resolve(xhr.response)
- }else{
- reject('出错了')
- }
- }
- }
- // 整理url中的参数
- let str=''
- for(key in data){
- str += `${key}=${data[key]}`
- }
- xhr.open('GET',url+'?'+ str)
- xhr.responseType="json"
- xhr.send()
- })
- )
- }
- sentAjax('https://api.github.com/search/users4',{q:2})
- .then(
- value=>{
- console.log('第一次成功了',value)
- return sentAjax('https://api.github.com/search/users',{q:3})
- },
- // reason=>{throw reason} //底层默认填补
- )
- .then(
- value=>{
- console.log('第二次成功了',value)
- return sentAjax('https://api.github.com/search/users',{q:4})
- },
- // reason=>{throw reason}
- )
- .then(
- value=>{console.log('第三次成功了',value)},
- // reason=>{throw reason}
- )
- .catch(
- reason=>{console.log(reason)}
- )
- </script>