目录
1. 作用:和并请求
2. 返回所有请求成功之后,返回数组,状态:fulfilled
3. 返回所有请求中第一次抛出的错误,状态:rejected
4. 如果在子请求中使用catch处理过了错误,则promise.all不会返回这个错误,如果剩下的都成功则返回一个数组,catch处理过的值为undefined
不管成功还是失败都是等全部结束,返回一个数组
返回第一个成功的回调,在第一个成功
- (function () {
- // promise.all
- // 1. 作用:和并请求
- // 2. 返回所有请求成功之后,返回数组,状态:fulfilled
- // 3. 返回所有请求中第一次抛出的错误,状态:rejected
- // 4. 如果在子请求中使用catch处理过了错误,则promise.all不会返回这个错误,如果剩下的都成功则返回一个数组,catch处理过的值为undefined
-
- // allSettled 不管成功还是失败都是等全部结束,返回一个数组
-
- // any 返回第一个成功的回调,在第一个成功的回调之前,任意一个实例已经进行了。then或者。catch的处理,则返回:成功fulfilled-undefined
-
- let p1 = new Promise((resolve, reject) => {
- reject('失败')
- setTimeout(() => {
- resolve('chengg1')
-
- }, 1000)
- })
- let p2 = new Promise((resolve, reject) => {
- setTimeout(() => {
-
- resolve('成功2')
- }, 3000)
- })
- // .then((res)=>{
- // console.log('resp2', res)
- // })
- let p3 = new Promise((resolve, reject) => {
- setTimeout(() => {
-
- resolve('cheng3')
- }, 4999)
- })
- // .then((res)=>{
- // console.log('resp3', res)
- // })
-
- let all = Promise.allSettled([p1, p2, p3])
- .then(
- (value) => {
- console.log('value-any', value)
- console.log(all, 'all')
- }, (reason) => {
- console.log('reason-any', reason)
-
- })
-
- console.log(all, 'all')
-
- })()
返回第一个状态结束的
- (function () {
-
- //将多个promise实例包装成一个新的promise实例
- //1. 返回一个,实例中改变状态的值
-
- function r1() {
- return new Promise((resolve, reject) => {
- setTimeout(()=>{
- resolve('请求成功')
- },3000)
- })
- }
-
- function r2() {
- return new Promise((reslove, reject) => {
- setTimeout(()=>{
- reslove('请求超时')
- },2000)
- })
- }
-
- Promise.race([r1(),r2()]).then((value)=>{
- console.log('value', value) // 请求超时
- })
-
- })()
- (function(){
-
- // 封装ajax
- // 请求 https://api.github.com/search/users?q=xx
- function Ajax(url){
- return new Promise((resolve,reject)=>{
- //1. 创建
- let xhr = new XMLHttpRequest()
- xhr.open('GET',url,true)
- xhr.send(null)
-
- xhr.onreadystatechange = function(){
-
- if(xhr.readyState!==4) return
- if (xhr.status>=200 && xhr.status<300) {
- resolve(xhr.response)
- }else {
- // console.log(xhr.statusText)
- reject(new Error(xhr.status))
- }
- }
- xhr.onerror = function(){
- reject(new Error(xhr.statusText))
- }
- xhr.responseType = 'json'
- })
- }
-
- Ajax('https://api.github.com/search/users?q=tian')
- .then(
- (value)=>{
- console.log(value)
- },
- (reason)=>{
- console.log(reason)
- }
- )
- })()
多个串联的异步操作
第一个.then 里面返回一个promise对象,第二个.then就是第一个返回的那个promise对象