当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Javascript Promise.all()用法及代码示例


Promise.all()方法实际上是一个promise,它将一个promise(可迭代)数组作为输入。它返回一个Promise,该Promise将在所有的诺言作为可迭代项传递时解决,或者当可迭代项不包含任何诺言时进行解决。以简单的方式,如果passed-in中的任何一个Promise被拒绝,则Promise.all()方法异步地拒绝已经被拒绝的Promise的值,而其他承诺是否已经解决。

用法:

Promise.all( iterable )

参数:此方法接受单个参数iterable,该参数采用promises数组或包含某些对象的普通数组。


返回值:它遵循一些规则以返回单个承诺:

  • 如果传递的参数为空,则返回已解决的Promise。
  • 如果传递的iterable不包含诺言,它将返回异步解决的Promise。
  • 对于所有其他情况,它将返回一个未决的Promise。

承诺的履行与拒绝all()方法:
履行:返回的诺言已兑现,

  • 如果传递的iterable为空,则此方法同步返回已解决的Promise。
  • 如果所有通过的承诺均得到履行,则返回的承诺将异步实现。

拒绝:如果任何传递的承诺都被拒绝,则此方法将拒绝该承诺的值,无论其他承诺是否已解决。

以下示例说明了JavaScript Promise.all()方法:

范例1:Promise.all等待实现

<script> 
    p1 = Promise.resolve(50); 
    p2 = 200 
    p3 = new Promise(function(resolve, reject) { 
        setTimeout(resolve, 100, 'geek'); 
    }); 
  
    Promise.all([p1, p2, p3]).then(function(values) { 
        document.write(values); 
    });  
</script>

输出:

50, 200, geek

范例2:这里Promise.all在2000 ms之后解析,输出显示为数组。

<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 => document.write(result+"<br>"))  
// Completed in 1000 
  
// Promise.all 
Promise.all([tOut(1000), tOut(2000)]).then(result => document.write(result)) 
</script>

输出:

Completed in 1000
Completed in 1000, Completed in 2000

在这里,Promise.all是兑现承诺的顺序。数组中的第一个promise将解析为输出数组的第一个元素,第二个promise将为输出数组中的第二个元素,依此类推。

范例3:在这里,Promise.all等到所有的诺言都化为乌有。

<script> 
// Simple promise that resolves after a given time 
const tOut = (t) => { 
  return new Promise((resolve, reject) => { 
    setTimeout(() => { 
      resolve(`Completed in ${t}`) 
    }, t) 
  }) 
} 
  
// Array contains some time duration 
const durations = [1000, 2000, 3000]  
  
const promises = []  // Empty array 
  
durations.map((duration) => { 
    
    // Calling the async function timeout(), so  
    // at this point the async function has started 
    // and enters the 'pending' state  
    // pushing the pending promise to an array. 
  promises.push(tOut(duration))  
}) 
  
document.write(promises) 
  
// Passing an array of pending promises to Promise.all 
// Promise.all will wait till all the promises get resolves 
// and then the same gets resolved. 
Promise.all(promises).then(response => document.write(response)) 
  
// It prints after previous promises gets resolved  
// ["Completed in 1000", "Completed in 2000", "Completed in 3000"] 
</script>

输出:

[object Promise], [object Promise], [object Promise]
.
.
. (gap between previous and last promises)
.
.
Completed in 1000, Completed in 2000, Completed in 3000

范例4:如果一个承诺失败,那么所有其他承诺都会失败。然后Promise.all被拒绝。

<script> 
// Promise that resolves after a given time 
const tOut = (t) => { 
  return new Promise((resolve, reject) => { 
    setTimeout(() => { 
      if (t === 2000) { 
        reject(`Rejected in ${t}`) 
      } else { 
        resolve(`Completed in ${t}`) 
      } 
    }, t) 
  }) 
} 
  
const durations = [1000, 2000, 3000] 
  
// Array contains some time durations 
const promises = [] //empty array 
  
durations.map((duration) => { 
    promises.push(tOut(duration)) 
    // Pushing durations in the promises array 
}) 
  
// Passing an array of pending promises to Promise.all 
Promise.all(promises).then(response => document.write(response))  
// Promise.all cannot be resolved, as one of the 
// promises passed, got rejected. 
  
.catch(error => document.write(`::Error::<br> ${error}`)) 
// Promise.all throws an error. 
</script>

输出:

Error
Rejected in 2000

支持的浏览器:JavaScript Promise.all()方法支持的浏览器如下:

  • 谷歌浏览器
  • 微软Edge
  • 火狐浏览器
  • 苹果Safari
  • Opera


相关用法


注:本文由纯净天空筛选整理自SoumikMondal大神的英文原创作品 JavaScript | Promise.all() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。