當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Javascript Promise.allSettled()用法及代碼示例

JavaScript中的Promise可以處於待處理,已實現或已拒絕的三種狀態。當解決了所有已實現或拒絕的輸入時,使用Javascript中的Promise.allSettled()方法獲得承諾。

用法:

Promise.allSettled(iterable);

參數:此方法接受一個可迭代的單個參數,該參數采用一個Promise數組或一個包含某些對象的普通數組。

返回值:此方法返回以下值:

  • 如果傳遞的參數為空,則返回已解決的Promise。
  • 對於所有其他情況,它將返回一個未決的Promise。

範例1:



Javascript

<script> 
    // Illustration of Promise.allSettled()  
    // Method in Javascript with Example 
  
    const p1 = Promise.resolve(50); 
    const p2 = new Promise((resolve, reject) =>  
                    setTimeout(reject, 100, 'geek')); 
    const prm = [p1, p2]; 
  
    Promise.allSettled(prm). 
      then((results) => results.forEach((result) =>  
      console.log(result.status,result.value))); 
</script>


輸出:

"fulfilled"
 50
"rejected" 
 undefined

範例2:

Javascript

<script> 
    // Simple promise that resolves  
    // After a given time  
    const tOut = (t) => {  
      return new Promise((resolve, reject) => {  
        setTimeout(() => {  
          resolve(`Completed in ${t}`)  
        }, t)  
      })  
    }  
    
    // Resolving a normal promise  
    tOut(1000).then(result => console.log(result))   
    // Completed in 1000  
    
    // Promise.allSettled  
    Promise.allSettled([tOut(1000), tOut(2000)]).then(result =>  
    console.log(result))  
</script>

輸出:

"Completed in 1000"
Array [Object { status:"fulfilled", value:"Completed in 1000" }, 
Object { status:"fulfilled", value:"Completed in 2000" }]

支持的瀏覽器:下麵列出了JavaScript Promise.allSettled()方法支持的瀏覽器:

  • 穀歌瀏覽器
  • 微軟邊
  • 火狐瀏覽器
  • 蘋果Safari
  • Opera

相關用法


注:本文由純淨天空篩選整理自shivanisinghss2110大神的英文原創作品 JavaScript | Promise.allSettled() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。