亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Javascript?promise.all的用法介紹(簡潔易懂)

 更新時間:2023年07月25日 08:53:31   作者:前端念初  
這篇文章主要給大家介紹了關(guān)于Javascript?promise.all用法的相關(guān)資料,Promise.all()方法是一個Promise對象方法,可以將多個Promise實例包裝成一個新的Promise對象,最終返回一個數(shù)組,需要的朋友可以參考下

前言

Promise對象的狀態(tài)改變,只有兩種可能:從pending變?yōu)閒ulfilled和從pending變?yōu)閞ejected。只要這兩種情況發(fā)生,狀態(tài)就凝固了,不會再變了,會一直保持這個結(jié)果,這時就稱為 resolved(已定型)。如果改變已經(jīng)發(fā)生了,你再對Promise對象添加回調(diào)函數(shù),也會立即得到這個結(jié)果。這與事件(Event)完全不同,事件的特點是,如果你錯過了它,再去監(jiān)聽,是得不到結(jié)果的。

promise.all()該方法用于將多個Promise實例,包裝成一個新的Promise實例。

   var p=Promise.all([p1,p2,p3]);

(1)只有p1、p2、p3的狀態(tài)都變成fulfilled,p的狀態(tài)才會變成fulfilled,此時p1、p2、p3的返回值組成一個數(shù)組,傳遞給p的回調(diào)函數(shù)。

(2)只要p1、p2、p3之中有一個被rejected,p的狀態(tài)就變成rejected,此時第一個被reject的實例的返回值,會傳遞給p的回調(diào)函數(shù)。

promise.all()

 比如當(dāng)數(shù)組里的P1,P2都執(zhí)行完成時,頁面才顯示。 值得注意的是,返回的數(shù)組結(jié)果順序不會改變,即使P2的返回要比P1的返回快,順序依然是P1, P2

    Promise.all成功返回成功數(shù)組,失敗返回失敗數(shù)據(jù),一但失敗就不會繼續(xù)往下走

let p1 = new Promise((resolve, reject) => {
  resolve('成功了')
})
 
let p2 = new Promise((resolve, reject) => {
  resolve('success')
})
 
let p3 = Promse.reject('失敗')
 
Promise.all([p1, p2]).then((result) => {
  console.log(result)               //['成功了', 'success']
}).catch((error) => {
  console.log(error)
})
 
Promise.all([p1,p3,p2]).then((result) => {
  console.log(result)
}).catch((error) => {
  console.log(error)      // 失敗了,打出 '失敗'
})
let wake = (time) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(`${time / 1000}秒后醒來`)
    }, time)
  })
}
 
let p1 = wake(3000)
let p2 = wake(2000)
 
Promise.all([p1, p2]).then((result) => {
  console.log(result)       // [ '3秒后醒來', '2秒后醒來' ]
}).catch((error) => {
  console.log(error)
})
 
需要特別注意的是,Promise.all獲得的成功結(jié)果的數(shù)組里面的數(shù)據(jù)順序和
Promise.all接收到的數(shù)組順序是一致的,即p1的結(jié)果在前,即便p1的結(jié)果
獲取的比p2要晚。這帶來了一個絕大的好處:在前端開發(fā)請求數(shù)據(jù)的過程中,
偶爾會遇到發(fā)送多個請求并根據(jù)請求順序獲取和使用數(shù)據(jù)的場景,
使用Promise.all毫無疑問可以解決這個問題。
注意:如果作為參數(shù)的 Promise 實例,自己定義了catch方法,那么它一旦被rejected,
并不會觸發(fā)Promise.all()的catch方法。
 
示例代碼:
 
const p1 = new Promise((resolve, reject) => {
  resolve('hello');
})
.then(result => result)
.catch(e => e);
 
const p2 = new Promise((resolve, reject) => {
  throw new Error('報錯了');
})
.then(result => result)
.catch(e => e);
 
Promise.all([p1, p2])
.then(result => console.log(result))
.catch(e => console.log(e));// ["hello", Error: 報錯了]
 
p1會resolved,p2首先會rejected,但是p2有自己的catch方法,該方法返回的是一個
新的 Promise 實例,p2指向的實際上是這個實例。
該實例執(zhí)行完catch方法后,也會變成resolved,導(dǎo)致Promise.all()方法參數(shù)里面的兩個實
例都會resolved,因此會調(diào)用then方法指定的回調(diào)函數(shù),而不會調(diào)用catch方法指定的回調(diào)函數(shù)。
 
而如果p2沒有自己的catch方法,就會調(diào)用Promise.all()的catch方法。如下:
 
const p1 = new Promise((resolve, reject) => {
  resolve('hello');
})
.then(result => result);
 
const p2 = new Promise((resolve, reject) => {
  throw new Error('報錯了');
})
.then(result => result);
 
Promise.all([p1, p2])
.then(result => console.log(result))
.catch(e => console.log(e));// Error: 報錯了

promise.race( )

Promise.race是賽跑的意思,也就是說Promise.race([p1, p2, p3])里面的結(jié)果哪個獲取的快,就返回哪個結(jié)果,不管結(jié)果本身是成功還是失敗

 使用場景: Promise.all和Promise.race都是有使用場景的。 有些時候我們做一個操作可能得同時需要不同的接口返回的數(shù)據(jù),這時我們就可以使用Promise.all; 有時我們比如說有好幾個服務(wù)器的好幾個接口都提供同樣的服務(wù),我們不知道哪個接口更快,就可以使用Promise.race,哪個接口的數(shù)據(jù)先回來我們就用哪個接口的數(shù)據(jù)

let p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('success')
  },1000)
})
 
let p2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject('failed')
  }, 500)
})
 
Promise.race([p1, p2]).then((result) => {
  console.log(result)
}).catch((error) => {
  console.log(error)  // 打開的是 'failed'
})

下面來看幾個簡潔易懂的例子:

1.await 可以獲得多個promise 的返回結(jié)果

2. Promise.all 返回的也是promise,所以可以直接await Promise.all();

1. 使用Promise

function fn(){
    return new Promise((resolve,reject)=>{
        let randomNum = parseInt(Math.random()*6+1);
        console.log(randomNum);
        if(randomNum>3){
            resolve('買'); 
        }
        else{
            reject('不買');
        }
    })
}
Promise.all([fn(),fn()]).then(
  (x)=>{console.log(x,'success')},(y)=>{console.log(y,'error');
});

Promise.all 里面參數(shù)為一個數(shù)組,數(shù)組的每一項是一個返回promise 的函數(shù)調(diào)用then 的第一個參數(shù)是所有promise都成功的調(diào)用,返回結(jié)果是一個數(shù)組,數(shù)組的每一項為函數(shù)promise 的返回結(jié)果。then 的第二個參數(shù):返回結(jié)果有一個失敗則執(zhí)行失敗的回調(diào),拿到的是第一個失敗的值

2. 使用await

await 是可以獲得多個promise 返回結(jié)果的,Promise.all()返回的也是promise結(jié)果。所以想要使用await 拿到多個promise的返回值,可以直接await Promise.all();

function fn(){
    return new Promise((resolve,reject)=>{
        let randomNum = parseInt(Math.random()*6+1);
        console.log(randomNum);
        if(randomNum>3){
            resolve('買'); 
        }
        else{
            reject('不買');
        }
    })
}
async function test(){
    try{
    let res = await Promise.all([fn(),fn()]);
    console.log(res,'success');
    }
    catch(error){
        console.log(error,'error');
    }
}
test();

Promise.all([fn(),fn()]) 都返回resolve(); 才能夠拿到成功的返回值Promise.all([fn(),fn()]) 有一個返回reject(), 則進入catch(error), 拿到失敗的返回值

 總結(jié)

到此這篇關(guān)于Javascript promise.all的用法介紹的文章就介紹到這了,更多相關(guān)promise.all用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論