MDN’s new design is in Beta! A sneak peek: https://blog.mozilla.org/opendesign/mdns-new-design-beta/

Promise.race()

翻譯不完整。請協助 翻譯此英文文件

Promise.race(iterable) 方法會回傳一個 promise 物件,此 promise 物件會於 iterable 參數中任一個 promise 轉為 resolve 或 rejected 時立即轉變成 resolve 或 rejected,並且接收其值或訊息。

語法

Promise.race(iterable);

參數

iterable
An iterable object, such as an Array. See iterable.

回傳值

A Promise that resolves or rejects as soon as one of the promises in the given iterable resolves or rejects.

描述

The race function returns a Promise that is settled the same way as the first passed promise to settle. It resolves or rejects, whichever happens first.

範例

Using Promise.race – examples with setTimeout

var p1 = new Promise(function(resolve, reject) { 
    setTimeout(resolve, 500, 'one'); 
});
var p2 = new Promise(function(resolve, reject) { 
    setTimeout(resolve, 100, 'two'); 
});

Promise.race([p1, p2]).then(function(value) {
  console.log(value); // "two"
  // Both resolve, but p2 is faster
});

var p3 = new Promise(function(resolve, reject) { 
    setTimeout(resolve, 100, 'three');
});
var p4 = new Promise(function(resolve, reject) { 
    setTimeout(reject, 500, 'four'); 
});

Promise.race([p3, p4]).then(function(value) {
  console.log(value); // "three"
  // p3 is faster, so it resolves
}, function(reason) {
  // Not called
});

var p5 = new Promise(function(resolve, reject) { 
    setTimeout(resolve, 500, 'five'); 
});
var p6 = new Promise(function(resolve, reject) { 
    setTimeout(reject, 100, 'six');
});

Promise.race([p5, p6]).then(function(value) {
  // Not called
}, function(reason) {
  console.log(reason); // "six"
  // p6 is faster, so it rejects
});

規範

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Promise.race' in that specification.
Standard Initial definition in an ECMA standard.
ECMAScript Latest Draft (ECMA-262)
The definition of 'Promise.race' in that specification.
Draft

覽瀏器相容性

Feature Chrome Edge Firefox Internet Explorer Opera Safari Servo
Basic Support32.0(Yes)29.0No support197.1No support
Feature Android Chrome for Android Edge Mobile Firefox for Android IE Mobile Opera Mobile Safari Mobile
Basic Support4.4.432.0(Yes)29No support(Yes)8.0

參見

文件標籤與貢獻者

 此頁面的貢獻者: jackblackevo
 最近更新: jackblackevo,