最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

前言

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

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

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

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

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

promise.all()

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

    Promise.all成功返回成功數(shù)組,失敗返回失敗數(shù)據(jù),一但失敗就不會(huì)繼續(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}秒后醒來(lái)`)
    }, time)
  })
}
 
let p1 = wake(3000)
let p2 = wake(2000)
 
Promise.all([p1, p2]).then((result) => {
  console.log(result)       // [ '3秒后醒來(lái)', '2秒后醒來(lái)' ]
}).catch((error) => {
  console.log(error)
})
 
需要特別注意的是,Promise.all獲得的成功結(jié)果的數(shù)組里面的數(shù)據(jù)順序和
Promise.all接收到的數(shù)組順序是一致的,即p1的結(jié)果在前,即便p1的結(jié)果
獲取的比p2要晚。這帶來(lái)了一個(gè)絕大的好處:在前端開(kāi)發(fā)請(qǐng)求數(shù)據(jù)的過(guò)程中,
偶爾會(huì)遇到發(fā)送多個(gè)請(qǐng)求并根據(jù)請(qǐng)求順序獲取和使用數(shù)據(jù)的場(chǎng)景,
使用Promise.all毫無(wú)疑問(wèn)可以解決這個(gè)問(wèn)題。
注意:如果作為參數(shù)的 Promise 實(shí)例,自己定義了catch方法,那么它一旦被rejected,
并不會(huì)觸發(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('報(bào)錯(cuò)了');
})
.then(result => result)
.catch(e => e);
 
Promise.all([p1, p2])
.then(result => console.log(result))
.catch(e => console.log(e));// ["hello", Error: 報(bào)錯(cuò)了]
 
p1會(huì)resolved,p2首先會(huì)rejected,但是p2有自己的catch方法,該方法返回的是一個(gè)
新的 Promise 實(shí)例,p2指向的實(shí)際上是這個(gè)實(shí)例。
該實(shí)例執(zhí)行完catch方法后,也會(huì)變成resolved,導(dǎo)致Promise.all()方法參數(shù)里面的兩個(gè)實(shí)
例都會(huì)resolved,因此會(huì)調(diào)用then方法指定的回調(diào)函數(shù),而不會(huì)調(diào)用catch方法指定的回調(diào)函數(shù)。
 
而如果p2沒(méi)有自己的catch方法,就會(huì)調(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('報(bào)錯(cuò)了');
})
.then(result => result);
 
Promise.all([p1, p2])
.then(result => console.log(result))
.catch(e => console.log(e));// Error: 報(bào)錯(cuò)了

promise.race( )

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

 使用場(chǎng)景: Promise.all和Promise.race都是有使用場(chǎng)景的。 有些時(shí)候我們做一個(gè)操作可能得同時(shí)需要不同的接口返回的數(shù)據(jù),這時(shí)我們就可以使用Promise.all; 有時(shí)我們比如說(shuō)有好幾個(gè)服務(wù)器的好幾個(gè)接口都提供同樣的服務(wù),我們不知道哪個(gè)接口更快,就可以使用Promise.race,哪個(gè)接口的數(shù)據(jù)先回來(lái)我們就用哪個(gè)接口的數(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)  // 打開(kāi)的是 'failed'
})

下面來(lái)看幾個(gè)簡(jiǎn)潔易懂的例子:

1.await 可以獲得多個(gè)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ù)為一個(gè)數(shù)組,數(shù)組的每一項(xiàng)是一個(gè)返回promise 的函數(shù)調(diào)用then 的第一個(gè)參數(shù)是所有promise都成功的調(diào)用,返回結(jié)果是一個(gè)數(shù)組,數(shù)組的每一項(xiàng)為函數(shù)promise 的返回結(jié)果。then 的第二個(gè)參數(shù):返回結(jié)果有一個(gè)失敗則執(zhí)行失敗的回調(diào),拿到的是第一個(gè)失敗的值

2. 使用await

await 是可以獲得多個(gè)promise 返回結(jié)果的,Promise.all()返回的也是promise結(jié)果。所以想要使用await 拿到多個(gè)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()]) 有一個(gè)返回reject(), 則進(jìn)入catch(error), 拿到失敗的返回值

 總結(jié)

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

相關(guān)文章

最新評(píng)論

崇义县| 哈巴河县| 郸城县| 镇坪县| 南通市| 诸暨市| 大同市| 巫山县| 启东市| 新化县| 望城县| 奈曼旗| 象山县| 右玉县| 正安县| 中江县| 汝南县| 建水县| 永德县| 绵阳市| 白水县| 泊头市| 沙坪坝区| 周至县| 克拉玛依市| 新蔡县| 平和县| 汕尾市| 姚安县| 乌什县| 高青县| 武夷山市| 滨海县| 大安市| 义马市| 长春市| 惠安县| 上高县| 大石桥市| 兴义市| 阆中市|