欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

ES6?Promise.all的使用方法以及其細(xì)節(jié)詳解

 更新時間:2022年07月19日 10:21:25   作者:小姚同學(xué)要繼續(xù)加油呀  
Promise對象用于表示一個異步操作的最終完成(或失敗)及其結(jié)果值,下面這篇文章主要給大家介紹了關(guān)于ES6?Promise.all的使用方法以及其細(xì)節(jié)的相關(guān)資料,需要的朋友可以參考下

ES6 Promise.all用法

Promise的all方法提供了并行執(zhí)行異步操作的能力,并且在所有異步操作執(zhí)行完后才執(zhí)行回調(diào)。可以將多個 Promise 實例,包裝成一個新的 Promise 實例。

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

上面代碼中,Promise.all方法接受一個數(shù)組作為參數(shù),p1、p2、p3都是 Promise 實例,如果不是,就會先調(diào)用下面講到的Promise.resolve方法,將參數(shù)轉(zhuǎn)為 Promise 實例,再進一步處理。(Promise.all方法的參數(shù)可以不是數(shù)組,但必須具有 Iterator 接口,且返回的每個成員都是 Promise 實例。)

p的狀態(tài)由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ù)。

但是,這里有個需要注意的細(xì)節(jié)!

如果作為參數(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方法。

then方法也會把所有異步操作的結(jié)果放進一個數(shù)組中傳給then,就是下面的results。

Promise
.all([runAsync1(), runAsync2(), runAsync3()])
.then(function(results){
    console.log(results);
});

附:promise.all的異步用法

    const promise1 = Promise.resolve(3);
    const promise2 = 42;
    const promise3 = new Promise((resolve, reject) => {
      setTimeout(resolve, 100, 'foo');
    });
 
    Promise.all([promise1, promise2, promise3]).then((values) => {
      console.log(values);
    });
    // expected output: Array [3, 42, "foo"]

總結(jié)

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

相關(guān)文章

最新評論